背景
软件开发过程中,不可避免的是需要处理各种异常,甚至有一半以上的时间都是在处理各种异常情况,所以代码中就会出现大量的try {...} catch {...} finally {...} 代码块,不仅有大量的冗余代码,而且还影响代码的可读性。比较下面两张图,看看您现在编写的代码属于哪一种风格?然后哪种编码风格您更喜欢?。

上面的示例,还只是比较简单的方法,复杂一些的可能会有更多的try catch代码块。这将会严重影响代码的可读性、“美观性”。 所以如果是我的话,我肯定偏向于第二种,我可以把更多的精力放在业务代码的开发,同时代码也会变得更加简洁。 既然业务代码不显式地对异常进行捕获、处理,而异常肯定还是处理的,不然系统岂不是动不动就崩溃了,所以必须得有其他地方捕获并处理这些异常。那么问题来了,如何优雅的处理各种异常?
基础知识点认识:
下面我们先认识两个注解@RestControllerAdvice和@ExceptionHandler
@RestControllerAdvice注解定义全局异常处理类,此注解通过对异常的拦截实现的统一异常返回处理。
@ExceptionHandler 一个异常拦截器(处理器),指定某个或某些异常后,会捕获到相应的异常。
使用 @ControllerAdvice + @ExceptionHandler 进行全局的 Controller 层异常处理,只要设计得当,就再也不用在 Controller 层进行 try-catch 了!而且@Validated 校验器注解的异常,也可以一起处理,减少模板代码,减少编码量,提升扩展性和可维护性。
异常按阶段分类
异常按阶段分可分为Controller前的异常和service层异常,具体可参考下图

断言:
在定义统一异常处理类之前,先来介绍一下如何优雅的判定异常情况并抛异常。 用 Assert(断言) 替换 throw exception 想必 Assert(断言) 大家都很熟悉,比如 Spring 家族的 org.springframework.util.Assert,在我们写测试用例的时候经常会用到,使用断言能让我们编码的时候有一种非一般丝滑的感觉,比如:
有没有感觉第二种判定非空的写法很优雅,第一种写法则是相对丑陋的 if {...} 代码块。那么 神奇的 Assert.notNull() 背后到底做了什么呢?下面是 Assert 的部分源码:
可以看到,Assert 其实就是帮我们把 if {...} 封装了一下,是不是很神奇。虽然很简单,但不可否认的是编码体验至少提升了一个档次。那么我们能不能模仿org.springframework.util.Assert,也写一个断言类,不过断言失败后抛出的异常不是IllegalArgumentException 这些内置异常,而是我们自己定义的异常。下面让我们来尝试一下,详见Assert接口类。
- package com.XX.edu.common.exception.assertion;
-
- import com.XX.edu.common.exception.BaseException;
-
- import java.util.List;
-
- public interface Assert {
- /**
- * 创建异常
- */
- BaseException newException(Object... args);
- /**
- * 创建异常
- */
- BaseException newException(Throwable t, Object... args);
- /**
- *
断言对象obj非空。如果对象obj为空,则抛出异常
- *
- * @param obj 待判断对象
- */
- default void assertNotNull(Object obj) {
- if (obj == null) {
- throw newException(obj);
- }
- }
-
- /**
- *
断言对象obj非空。如果对象obj为空,则抛出异常
- *
异常信息message支持传递参数方式,避免在判断之前进行字符串拼接操作
- *
- * @param obj 待判断对象
- * @param args message占位符对应的参数列表
- */
- default void assertNotNull(Object obj, Object... args) {
- if (obj == null) {
- throw newException(args);
- }
- }
-
- /**
- * 如果为false抛出异常
- **/
- default void assertIsTrue(boolean res, Object... args) {
- if (!res) {
- throw newException(args);
- }
- }
-
- /**
- * 如果为true抛出异常
- **/
- default void assertIsFalse(boolean res, Object... args) {
- if (res) {
- throw newException(args);
- }
- }
-
- /**
- * 如果不为空抛出异常
- **/
- default void assertIsEmpty(Object obj, Object... args) {
-
- if (obj instanceof List) {
- if (obj != null && ((List) obj).size() > 0) {
- throw newException(args);
- }
- } else {
- if (obj != null) {
- throw newException(args);
- }
- }
- }
-
- /**
- * 如果为空抛出异常
- **/
- default void assertIsNotEmpty(Object obj, Object... args) {
- if (obj instanceof List) {
- if (obj == null || ((List) obj).size() == 0) {
- throw newException(args);
- }
- } else {
- if (obj == null) {
- throw newException(args);
- }
- }
- }
- }
上面的Assert断言方法是使用接口的默认方法定义的,然后有没有发现当断言失败后,抛出的异常不是具体的某个异常,而是交由2个newException接口方法提供。因为业务逻辑中出现的异常基本都是对应特定的场景,比如根据用户id获取用户信息,查询结果为null,此时抛出的异常可能为UserNotFoundException,并且有特定的异常码(比如7001)和异常信息“用户不存在”。所以具体抛出什么异常,有Assert的实现类决定。
看到这里,您可能会有这样的疑问,按照上面的说法,那岂不是有多少异常情况,就得有定义等量的断言类和异常类,这显然是不可行的。下面我们来将 Enum 和 Assert 结合起来。看能否解决这个问题。
先来看一张UML类图:

- package com.XX.edu.common.exception.enums;
-
- public interface IResponseEnum {
- /**
- * 获取返回码
- * @return 返回码
- */
- int getCode();
-
- /**
- * 获取返回信息
- * @return 返回信息
- */
- String getMessage();
- }
- package com.XX.edu.common.exception.assertion;
-
- import cn.hutool.core.util.ArrayUtil;
- import com.XX.edu.common.exception.ArgumentException;
- import com.XX.edu.common.exception.BaseException;
- import com.XX.edu.common.exception.enums.IResponseEnum;
-
- import java.text.MessageFormat;
-
-
- public interface CommonExceptionAssert extends IResponseEnum, Assert {
-
- @Override
- default BaseException newException(Object... args) {
- String msg = this.getMessage();
- if (ArrayUtil.isNotEmpty(args)) {
- msg = MessageFormat.format(this.getMessage(), args);
- }
-
- return new ArgumentException(this, args, msg);
- }
-
- @Override
- default BaseException newException(Throwable t, Object... args) {
- String msg = this.getMessage();
- if (ArrayUtil.isNotEmpty(args)) {
- msg = MessageFormat.format(this.getMessage(), args);
- }
-
- return new ArgumentException(this, args, msg, t);
- }
-
- }
- package com.XX.edu.common.exception.assertion;
-
- import com.XX.edu.common.exception.BaseException;
- import com.XX.edu.common.exception.BusinessException;
- import com.XX.edu.common.exception.enums.IResponseEnum;
-
- import java.text.MessageFormat;
- //接口可以继承多个接口
- public interface BusinessExceptionAssert extends IResponseEnum, Assert {
- //jdk8以后接口里面可以包含方法体,但必须使用default或static修饰,
- // 而且我们知道实现类如果继承了接口,实现类必须强制重现接口的方法,但是这两种方式是不需要强制重写的,相当于没有abstract修饰
- @Override
- default BaseException newException(Object... args) {
- String msg = MessageFormat.format(this.getMessage(), args);
-
- return new BusinessException(this, args, msg);
- }
-
- @Override
- default BaseException newException(Throwable t, Object... args) {
- String msg = MessageFormat.format(this.getMessage(), args);
-
- return new BusinessException(this, args, msg, t);
- }
-
- }
- package com.XX.edu.common.exception.enums;
-
- import com.XX.edu.common.exception.assertion.BusinessExceptionAssert;
- import lombok.AllArgsConstructor;
- import lombok.Getter;
-
- /**
- *
业务
- */
- @Getter
- @AllArgsConstructor
- public enum BusinessResponseEnum implements BusinessExceptionAssert {
-
- UNCLASSIFIED(5001, "根据课程id={0},班级id={1}未查询到班级信息"),
- UNEXERCISEiNFO(5002, "根据习题id={0}未查询到习题详情"),
- UNEXERCISE(5003, "习题id={0}不存在"),
- DUMPLICATEEXERCISE(5004, "习题ID={0}已在删除状态,不可重复删除"),
- CANNOTDELETEEXERCISE(5005, "习题ID={0}正在使用中,不可删除"),
- NOMIGRATIONEXERCISE(5006, "没有需要迁移的历史数据"),
- ;
- /**
- * 返回码
- */
- private int code;
- /**
- * 返回消息
- */
- private String message;
-
-
- }
- package com.XX.edu.common.exception.enums;
-
- import com.XX.edu.common.exception.assertion.CommonExceptionAssert;
- import lombok.AllArgsConstructor;
- import lombok.Getter;
-
- /**
- *
通用返回结果
- *
- */
- @Getter
- @AllArgsConstructor
- public enum CommonResponseEnum implements CommonExceptionAssert {
- /**
- * 成功
- */
- SUCCESS(0, "SUCCESS"),
- /**
- * 服务器繁忙,请稍后重试
- */
- SERVER_BUSY(9998, "服务器繁忙"),
- /**
- * 服务器异常,无法识别的异常,尽可能对通过判断减少未定义异常抛出
- */
- SERVER_ERROR(9999, "网络异常");
-
- /**
- * 返回码
- */
- private int code;
- /**
- * 返回消息
- */
- private String message;
-
-
- }
- package com.XX.edu.common.exception.enums;
-
- import com.XX.edu.common.exception.assertion.CommonExceptionAssert;
- import lombok.AllArgsConstructor;
- import lombok.Getter;
-
- /**
- *
参数校验异常返回结果
- *
- * @author sprainkle
- * @date 2019/5/2
- */
- @Getter
- @AllArgsConstructor
- public enum ArgumentResponseEnum implements CommonExceptionAssert {
- /**
- * 绑定参数校验异常
- */
- VALID_ERROR(6000, "参数校验异常");
-
- /**
- * 返回码
- */
- private int code;
- /**
- * 返回消息
- */
- private String message;
-
- }
- package com.XX.edu.common.exception.enums;
-
- import lombok.AllArgsConstructor;
- import lombok.Getter;
-
- import javax.servlet.http.HttpServletResponse;
-
- /**
- *
异常类与http status对照关系
- *
- * @author
- * @date 2022/11/1
- * @see org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
- */
- @Getter
- @AllArgsConstructor
- public enum ServletResponseEnum {
- MethodArgumentNotValidException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
- MethodArgumentTypeMismatchException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
- MissingServletRequestPartException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
- MissingPathVariableException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
- BindException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
- MissingServletRequestParameterException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
- TypeMismatchException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
- ServletRequestBindingException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
- HttpMessageNotReadableException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
- NoHandlerFoundException(4404, "", HttpServletResponse.SC_NOT_FOUND),
- NoSuchRequestHandlingMethodException(4404, "", HttpServletResponse.SC_NOT_FOUND),
- HttpRequestMethodNotSupportedException(4405, "", HttpServletResponse.SC_METHOD_NOT_ALLOWED),
- HttpMediaTypeNotAcceptableException(4406, "", HttpServletResponse.SC_NOT_ACCEPTABLE),
- HttpMediaTypeNotSupportedException(4415, "", HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE),
- ConversionNotSupportedException(4500, "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
- HttpMessageNotWritableException(4500, "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
- AsyncRequestTimeoutException(4503, "", HttpServletResponse.SC_SERVICE_UNAVAILABLE)
- ;
-
- /**
- * 返回码,目前与{@link #statusCode}相同
- */
- private int code;
- /**
- * 返回信息,直接读取异常的message
- */
- private String message;
- /**
- * HTTP状态码
- */
- private int statusCode;
- }
- package com.XX.edu.common.exception;
-
- import com.XX.edu.common.exception.enums.IResponseEnum;
- import lombok.Getter;
-
- /**
- * @Description: 异常基类
- * @Title: BaseException
- * @Package com.XX.edu.common.exception
- * @Author:
- * @Copyright
- * @CreateTime: 2022/11/1 13:43
- */
-
- @Getter
- public class BaseException extends RuntimeException {
- private static final long serialVersionUID = 1L;
-
- /**
- * 返回码
- */
- protected IResponseEnum responseEnum;
- /**
- * 异常消息参数
- */
- protected Object[] args;
-
- public BaseException(IResponseEnum responseEnum) {
- super(responseEnum.getMessage());
- this.responseEnum = responseEnum;
- }
-
- public BaseException(int code, String msg) {
- super(msg);
- this.responseEnum = new IResponseEnum() {
- @Override
- public int getCode() {
- return code;
- }
-
- @Override
- public String getMessage() {
- return msg;
- }
- };
- }
-
- public BaseException(IResponseEnum responseEnum, Object[] args, String message) {
- super(message);
- this.responseEnum = responseEnum;
- this.args = args;
- }
-
- public BaseException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
- super(message, cause);
- this.responseEnum = responseEnum;
- this.args = args;
- }
- }
- package com.XX.edu.common.exception;
-
-
- import com.XX.edu.common.exception.enums.IResponseEnum;
-
- /**
- *
参数异常
- *
在处理业务过程中校验参数出现错误, 可以抛出该异常
- *
编写公共代码(如工具类)时,对传入参数检查不通过时,可以抛出该异常
- *
- */
- public class ArgumentException extends BaseException {
-
- private static final long serialVersionUID = 1L;
-
- public ArgumentException(IResponseEnum responseEnum, Object[] args, String message) {
- super(responseEnum, args, message);
- }
-
- public ArgumentException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
- super(responseEnum, args, message, cause);
- }
- }
- package com.XX.edu.common.exception;
-
- import com.XX.edu.common.exception.enums.IResponseEnum;
-
- /**
- * @Description: 业务异常,业务处理时,出现异常,可以抛出该异常
- * @Title: BusinessException
- * @Package com.XX.edu.common.exception
- * @Author:
- * @Copyright
- * @CreateTime: 2022/11/1 13:32
- */
- public class BusinessException extends BaseException {
-
- private static final long serialVersionUID = 1L;
-
- public BusinessException(IResponseEnum responseEnum, Object[] args, String message) {
- super(responseEnum, args, message);
- }
-
- public BusinessException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
- super(responseEnum, args, message, cause);
- }
-
- }
- package com.XX.edu.common.exception.i18n;
-
- import org.springframework.context.MessageSource;
- import org.springframework.context.i18n.LocaleContextHolder;
- import org.springframework.stereotype.Service;
-
- import javax.annotation.Resource;
- import java.util.Locale;
-
- @Service
- public class UnifiedMessageSource {
-
- @Resource
- private MessageSource messageSource;
-
- /**
- * 获取国际化消息
- * @param code 消息code
- * @return
- */
- public String getMessage(String code) {
-
- return getMessage(code, null);
- }
-
- /**
- * 获取国际化消息
- * @param code 消息code
- * @param args 参数
- * @return
- */
- public String getMessage(String code, Object[] args) {
-
- return getMessage(code, args, "");
- }
-
- /**
- * 获取国际化消息
- * @param code 消息code
- * @param args 参数
- * @param defaultMessage 默认消息
- * @return
- */
- public String getMessage(String code, Object[] args, String defaultMessage) {
- Locale locale = LocaleContextHolder.getLocale();
-
- return messageSource.getMessage(code, args, defaultMessage, locale);
- }
- }
使用枚举类结合(继承)Assert,只需根据特定的异常情况定义不同的枚举实例,就能够针对不同情况抛出特定的异常(这里指携带特定的异常码和异常消息),这样既不用定义大量的异常类,同时还具备了断言的良好可读性。
使用:

全局异常处理
实际上异常只有两大类,一类是ServletException、ServiceException,还记得上文提到的 按阶段分类 吗,即对应 进入Controller前的异常 和 Service 层异常;然后 ServiceException 再分成自定义异常、未知异常。对应关系如下: 进入Controller前的异常: handleServletException、handleBindException、handleValidException 自定义异常: handleBusinessException、handleBaseException 未知异常: handleException
下面我们来看一下全局异常如何处理
- package com.XX.edu.common.exception.handler;
-
- /**
- * @Description: 定义统一异常处理器类
- * @Title: UnifiedExceptionHandler
- * @Package com.XX.edu.common.exception
- * @Author:
- * @Copyright
- * @CreateTime: 2022/11/1 14:02
- */
-
- import com.XX.edu.common.bean.ResultTO;
- import com.XX.edu.common.exception.BaseException;
- import com.XX.edu.common.exception.BusinessException;
- import com.XX.edu.common.exception.enums.ArgumentResponseEnum;
- import com.XX.edu.common.exception.enums.CommonResponseEnum;
- import com.XX.edu.common.exception.enums.ServletResponseEnum;
- import com.XX.edu.common.exception.i18n.UnifiedMessageSource;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.ConversionNotSupportedException;
- import org.springframework.beans.TypeMismatchException;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.http.converter.HttpMessageNotReadableException;
- import org.springframework.http.converter.HttpMessageNotWritableException;
- import org.springframework.validation.BindException;
- import org.springframework.validation.BindingResult;
- import org.springframework.validation.FieldError;
- import org.springframework.validation.ObjectError;
- import org.springframework.web.HttpMediaTypeNotAcceptableException;
- import org.springframework.web.HttpMediaTypeNotSupportedException;
- import org.springframework.web.HttpRequestMethodNotSupportedException;
- import org.springframework.web.bind.MethodArgumentNotValidException;
- import org.springframework.web.bind.MissingPathVariableException;
- import org.springframework.web.bind.MissingServletRequestParameterException;
- import org.springframework.web.bind.ServletRequestBindingException;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.RestControllerAdvice;
- import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
- import org.springframework.web.multipart.support.MissingServletRequestPartException;
- import org.springframework.web.servlet.NoHandlerFoundException;
-
-
- /**
- *
全局异常处理器
- */
- @RestControllerAdvice
- public class UnifiedExceptionHandler {
- Logger logger = LoggerFactory.getLogger(getClass());
- /**
- * 生产环境BusinessException
- */
- private final static String ENV_PROD = "prod";
-
- @Autowired
- private UnifiedMessageSource unifiedMessageSource;
- /**
- * 当前环境
- */
- @Value("${spring.profiles.active}")
- private String profile;
-
-
- /**
- * 自定义异常
- *
- * BaseException extends RuntimeException
- *
- * @param e 异常
- * @return 异常结果
- */
- @ExceptionHandler(value = BaseException.class)
- public ResultTO handleBaseException(BaseException e) {
- logger.error(e.getMessage(), e);
-
- return ResultTO.FAILURE(getMessage(e), e.getResponseEnum().getCode());
- }
-
- /**
- * 未定义异常
- *
- * @param e 异常
- * @return 异常结果
- */
- @ExceptionHandler(value = Exception.class)
- public ResultTO handleException(Exception e) {
- logger.error(e.getMessage(), e);
-
- if (ENV_PROD.equals(profile)) {
- // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如数据库异常信息.
- int code = CommonResponseEnum.SERVER_ERROR.getCode();
- BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR);
- String message = getMessage(baseException);
- return ResultTO.FAILURE(message, code);
- }
- return ResultTO.FAILURE(e.getMessage(), CommonResponseEnum.SERVER_ERROR.getCode());
- }
-
- /**
- * 业务异常
- *
- * @param e 异常
- * @return 异常结果
- */
- @ExceptionHandler(value = BusinessException.class)
- public ResultTO handleBusinessException(BaseException e) {
- logger.error(e.getMessage(), e);
-
- return ResultTO.FAILURE(getMessage(e),e.getResponseEnum().getCode());
- }
-
- /**
- * Controller上一层相关异常
- *
- * @param e 异常
- * @return 异常结果
- */
- @ExceptionHandler({
- NoHandlerFoundException.class,
- HttpRequestMethodNotSupportedException.class,
- HttpMediaTypeNotSupportedException.class,
- HttpMediaTypeNotAcceptableException.class,
- MissingPathVariableException.class,
- MissingServletRequestParameterException.class,
- TypeMismatchException.class,
- HttpMessageNotReadableException.class,
- HttpMessageNotWritableException.class,
- // BindException.class,
- // MethodArgumentNotValidException.class
- ServletRequestBindingException.class,
- ConversionNotSupportedException.class,
- MissingServletRequestPartException.class,
- AsyncRequestTimeoutException.class
- })
-
- public ResultTO handleServletException(Exception e) {
- logger.error(e.getMessage(), e);
- int code = CommonResponseEnum.SERVER_ERROR.getCode();
- try {
- ServletResponseEnum servletExceptionEnum = ServletResponseEnum.valueOf(e.getClass().getSimpleName());
- code = servletExceptionEnum.getCode();
- } catch (IllegalArgumentException e1) {
- logger.error("class [{}] not defined in enum {}", e.getClass().getName(), ServletResponseEnum.class.getName());
- }
-
- if (ENV_PROD.equals(profile)) {
- // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如404.
- code = CommonResponseEnum.SERVER_ERROR.getCode();
- BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR);
- String message = getMessage(baseException);
- return ResultTO.FAILURE(message, code);
- }
-
- return ResultTO.FAILURE(e.getMessage(), code);
- }
-
-
- /**
- * 参数绑定异常
- *
- * @param e 异常
- * @return 异常结果
- */
- @ExceptionHandler(value = BindException.class)
- public ResultTO handleBindException(BindException e) {
- logger.error("参数绑定校验异常", e);
-
- return wrapperBindingResult(e.getBindingResult());
- }
-
- /**
- * 参数校验(Valid)异常,将校验失败的所有异常组合成一条错误信息
- *
- * @param e 异常
- * @return 异常结果
- */
- @ExceptionHandler(value = MethodArgumentNotValidException.class)
- public ResultTO handleValidException(MethodArgumentNotValidException e) {
- logger.error("参数绑定校验异常", e);
-
- return wrapperBindingResult(e.getBindingResult());
- }
-
- /**
- * 包装绑定异常结果
- *
- * @param bindingResult 绑定结果
- * @return 异常结果
- */
- private ResultTO wrapperBindingResult(BindingResult bindingResult) {
- StringBuilder msg = new StringBuilder();
-
- for (ObjectError error : bindingResult.getAllErrors()) {
- msg.append(", ");
- if (error instanceof FieldError) {
- msg.append(((FieldError) error).getField()).append(": ");
- }
- msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
-
- }
-
- return ResultTO.FAILURE(msg.substring(2), ArgumentResponseEnum.VALID_ERROR.getCode());
- }
-
-
- /**
- * 获取国际化消息
- *
- * @param e 异常
- * @return
- */
- public String getMessage(BaseException e) {
- String code = "response." + e.getResponseEnum().toString();
- String message = unifiedMessageSource.getMessage(code, e.getArgs());
-
- if (message == null || message.isEmpty()) {
- return e.getMessage();
- }
- return message;
- }
-
- }
这样项目抛出的异常就会到异常处理类中统一处理~~
收工~!!