全局异常处理器-SpringBoot
定义:把错误异常统一处理的方法。
好处:
- 避免在业务层中写大量的try/catch,降低代码冗余
- 自定义异常,让我们可以实际情况对业务异常返回更细致、更明确的结果
怎么封装全局异常处理器(以我项目中封装的为例)
-
封装统一返回结果类
public class ResultUtils { /** * 成功 * * @param data * @param <T> * @return */ public static <T> BaseResponse<T> success(T data) { return new BaseResponse<>(0, data, "ok"); } /** * 失败 * * @param errorCode * @return */ public static BaseResponse error(ErrorCode errorCode) { return new BaseResponse<>(errorCode); } /** * 失败 * * @param code * @param message * @return */ public static BaseResponse error(int code, String message) { return new BaseResponse(code, null, message); } /** * 失败 * * @param errorCode * @return */ public static BaseResponse error(ErrorCode errorCode, String message) { return new BaseResponse(errorCode.getCode(), null, message); } }
-
自定义异常
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; } }
-
封装全局异常处理器
/** * 全局异常处理器 * * @author <a href="https://github.com/JianHuaDeng">程序员Hua</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, "系统错误"); } }