本文介绍了在Spring Boot项目中自定义异常处理机制的具体方法,包括如何设置个性化的错误码及对应的提示信息。
在 Spring Boot 中自定义返回错误码与错误信息是一个关键功能,它有助于开发者更好地处理并传递错误给调用端。本段落将详细介绍如何在 Spring Boot 应用中实现这一特性,并提供相关代码示例。
首先,我们需要创建一个枚举类 `ErrorEnum` 来列举所有可能的错误码和对应的描述信息:
```java
public enum ErrorEnum {
E_20011(20011, 缺少必填参数),
// 这里添加其他错误代码与消息
private Integer errorCode;
private String errorMsg;
ErrorEnum(Integer errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public Integer getErrorCode() {
return errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
}
```
接下来,定义一个异常类 `BusinessException` 来封装错误码和消息:
```java
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 1L;
private Integer code;
public BusinessException(ErrorEnum errorEnum) {
super(errorEnum.getErrorMsg());
this.code = errorEnum.getErrorCode();
// 这里可以添加一些额外的处理逻辑,例如生成错误响应JSON
}
public Integer getCode() {
return code;
}
}
```
为了统一异常返回格式,我们还需要创建一个 `ExceptionResponse` 类:
```java
public class ExceptionResponse {
private String message;
private Integer code;
public ExceptionResponse(Integer code, String message) {
this.message = message;
this.code = code;
}
public static ExceptionResponse create(Integer code, String message) {
return new ExceptionResponse(code, message);
}
// Getter 方法
}
```
最后,我们需要实现一个全局异常处理器 `ExceptionHandler` 来捕获并响应所有抛出的异常:
```java
@ControllerAdvice
public class ExceptionHandler {
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public ExceptionResponse handleException(Exception ex) {
if (ex instanceof BusinessException) {
// 记录错误日志(可选)
return new ExceptionResponse(((BusinessException) ex).getCode(), ((BusinessException) ex).getMessage());
}
// 处理其他类型的异常
}
}
```
通过以上步骤,我们可以在 Spring Boot 应用中有效地自定义和返回错误码及信息。