默认情况下,Spring Boot 出错时,页面显示如下格式的错误信息:
Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Sun Dec 12 11:18:04 CST 2021 There was an unexpected error (type=Not Found, status=404).
原理:使用 @RestControllerAdvice 加 @ExceptionHandler 注解来实现,
- 注意:@RestControllerAdvice只能拦截Controller层的异常不会拦截Interceptor的异常;
- 优点:把异常统一处理,减少代码的重复编写,提高了可维护性;
- 缺点:只能处理Controller层的异常,对于Interceptor层的异常,Spring内部的异常无能为力;
【推荐】SpringBoot系列(十)统一异常处理与统一结果返回(优化:把里面的 @ControllerAdvice 和 @ResponseBody 删掉,换成 @RestControllerAdvice)
Spring Boot @RestControllerAdvice 统一异常处理
【工作笔记】
1.全局异常类:
package love.hibotella.common.exception; import love.hibotella.common.model.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * 全局异常处理 */ @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(value = Exception.class) public Result<Object> exceptionHandler(Exception e) { logger.error(e.getMessage(), e); ErrorEnum serverError = ErrorEnum.INTERNAL_SERVER_ERROR; return Result.error(serverError.getErrorCode(), serverError.getErrorMsg(), null); } }
2.错误枚举类:
package love.hibotella.common.exception; /** * 常用异常 枚举 */ public enum ErrorEnum { SUCCESS("200", "操作成功"), NO_AUTH("401", "请先登录"), NO_PERMISSION("403", "没有权限"), NOT_FOUND("404", "未找到该资源"), INTERNAL_SERVER_ERROR("500", "服务器内部错误"), ; /** * 错误码 */ private String errorCode; /** * 错误信息 */ private String errorMsg; ErrorEnum(String errorCode, String errorMsg) { this.errorCode = errorCode; this.errorMsg = errorMsg; } public String getErrorCode() { return errorCode; } public String getErrorMsg() { return errorMsg; } }
3.Result<T> 业务结果类: