为什么要进行全局异常处理
在 JavaEE 项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的、不可预知的异常需要处理。每个过程都单独处理异常,系统的代码耦合度高,工作量大且不好统一,维护的工作量也很大。
全局异常处理的好处
1、不用在业务层中写try/catch,异常统一交给全局异常处理器去捕获和处理,降低代码冗余;
2、可以自定义异常,根据实际情况对业务异常进行更细致和明确的拓展;
3、配置简单,将代码复制到项目中即可使用
效果预览
我们使用经典的“1/0”在程序中模拟异常的发生。
未进行全局异常处理之前
可以看到,返回的响应体包含密密麻麻的一大段冗余报错,其实这么一长串无非想表达的就是“/ by zero” 这个错误罢了。
进行全局异常处理之后
进行异常处理后可以看到返回的结果报错信息非常清晰~
怎么实现
说了那么多,那么到底怎么实现呢,其实非常简单,使用spring的aop即可实现
1、封装统一返回结果类
封装返回结果实体类,统一返回结果数据格式,不懂统一返回结果类的小伙伴可以具体看看这篇文章 https://mp.csdn.net/mp_blog/creation/editor/132510145
/**
* 通用返回类
* @param <T>
* @author <a href="https://gitee.com/re_lq">RE_LQ</a>
*/
@Data
public class BaseResponse<T> implements Serializable {
private int code;
private T data;
private String message;
public BaseResponse(int code, T data, String message) {
this.code = code;
this.data = data;
this.message = message;
}
public BaseResponse(int code, T data) {
this(code, data, "");
}
public BaseResponse(ErrorCode errorCode) {
this(errorCode.getCode(), null, errorCode.getMessage());
}
}
2、自定义异常类
自定义异常类,用于自定义异常抛出,根据实际情况对业务异常进行更细致和明确的拓展
/**
* 自定义异常类
*
*/
public class BusinessException extends RuntimeException {
/**
* 错误码
*/
private final int code;
public BusinessException(int code, String message) {
super(message);
this.code = code;
}
public BusinessException(ErrorCode errorCode) {
super(errorCode.getMessage());
this.code = errorCode.getCode();
}
public BusinessException(ErrorCode errorCode, String message) {
super(message);
this.code = errorCode.getCode();
}
public int getCode() {
return code;
}
}
3、定义全局异常处理类
/**
* 全局异常处理器
* @author <a href="https://gitee.com/re_lq">RE_LQ</a>
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public BaseResponse<?> businessExceptionHandler(BusinessException e) {
log.error("BusinessException", e);
return ResultUtils.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(RuntimeException.class)
public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
log.error("RuntimeException", e);
return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
}
}