• 代码中统一异常如何处理,才能让代码更清晰


    背景

    软件开发过程中,不可避免的是需要处理各种异常,甚至有一半以上的时间都是在处理各种异常情况,所以代码中就会出现大量的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接口类。

    1. package com.XX.edu.common.exception.assertion;
    2. import com.XX.edu.common.exception.BaseException;
    3. import java.util.List;
    4. public interface Assert {
    5. /**
    6. * 创建异常
    7. */
    8. BaseException newException(Object... args);
    9. /**
    10. * 创建异常
    11. */
    12. BaseException newException(Throwable t, Object... args);
    13. /**
    14. *

      断言对象obj非空。如果对象obj为空,则抛出异常

    15. *
    16. * @param obj 待判断对象
    17. */
    18. default void assertNotNull(Object obj) {
    19. if (obj == null) {
    20. throw newException(obj);
    21. }
    22. }
    23. /**
    24. *

      断言对象obj非空。如果对象obj为空,则抛出异常

    25. *

      异常信息message支持传递参数方式,避免在判断之前进行字符串拼接操作

    26. *
    27. * @param obj 待判断对象
    28. * @param args message占位符对应的参数列表
    29. */
    30. default void assertNotNull(Object obj, Object... args) {
    31. if (obj == null) {
    32. throw newException(args);
    33. }
    34. }
    35. /**
    36. * 如果为false抛出异常
    37. **/
    38. default void assertIsTrue(boolean res, Object... args) {
    39. if (!res) {
    40. throw newException(args);
    41. }
    42. }
    43. /**
    44. * 如果为true抛出异常
    45. **/
    46. default void assertIsFalse(boolean res, Object... args) {
    47. if (res) {
    48. throw newException(args);
    49. }
    50. }
    51. /**
    52. * 如果不为空抛出异常
    53. **/
    54. default void assertIsEmpty(Object obj, Object... args) {
    55. if (obj instanceof List) {
    56. if (obj != null && ((List) obj).size() > 0) {
    57. throw newException(args);
    58. }
    59. } else {
    60. if (obj != null) {
    61. throw newException(args);
    62. }
    63. }
    64. }
    65. /**
    66. * 如果为空抛出异常
    67. **/
    68. default void assertIsNotEmpty(Object obj, Object... args) {
    69. if (obj instanceof List) {
    70. if (obj == null || ((List) obj).size() == 0) {
    71. throw newException(args);
    72. }
    73. } else {
    74. if (obj == null) {
    75. throw newException(args);
    76. }
    77. }
    78. }
    79. }

     上面的Assert断言方法是使用接口的默认方法定义的,然后有没有发现当断言失败后,抛出的异常不是具体的某个异常,而是交由2个newException接口方法提供。因为业务逻辑中出现的异常基本都是对应特定的场景,比如根据用户id获取用户信息,查询结果为null,此时抛出的异常可能为UserNotFoundException,并且有特定的异常码(比如7001)和异常信息“用户不存在”。所以具体抛出什么异常,有Assert的实现类决定。

    看到这里,您可能会有这样的疑问,按照上面的说法,那岂不是有多少异常情况,就得有定义等量的断言类和异常类,这显然是不可行的。下面我们来将 Enum 和 Assert 结合起来。看能否解决这个问题。

    先来看一张UML类图:

    1. package com.XX.edu.common.exception.enums;
    2. public interface IResponseEnum {
    3. /**
    4. * 获取返回码
    5. * @return 返回码
    6. */
    7. int getCode();
    8. /**
    9. * 获取返回信息
    10. * @return 返回信息
    11. */
    12. String getMessage();
    13. }
    1. package com.XX.edu.common.exception.assertion;
    2. import cn.hutool.core.util.ArrayUtil;
    3. import com.XX.edu.common.exception.ArgumentException;
    4. import com.XX.edu.common.exception.BaseException;
    5. import com.XX.edu.common.exception.enums.IResponseEnum;
    6. import java.text.MessageFormat;
    7. public interface CommonExceptionAssert extends IResponseEnum, Assert {
    8. @Override
    9. default BaseException newException(Object... args) {
    10. String msg = this.getMessage();
    11. if (ArrayUtil.isNotEmpty(args)) {
    12. msg = MessageFormat.format(this.getMessage(), args);
    13. }
    14. return new ArgumentException(this, args, msg);
    15. }
    16. @Override
    17. default BaseException newException(Throwable t, Object... args) {
    18. String msg = this.getMessage();
    19. if (ArrayUtil.isNotEmpty(args)) {
    20. msg = MessageFormat.format(this.getMessage(), args);
    21. }
    22. return new ArgumentException(this, args, msg, t);
    23. }
    24. }
    1. package com.XX.edu.common.exception.assertion;
    2. import com.XX.edu.common.exception.BaseException;
    3. import com.XX.edu.common.exception.BusinessException;
    4. import com.XX.edu.common.exception.enums.IResponseEnum;
    5. import java.text.MessageFormat;
    6. //接口可以继承多个接口
    7. public interface BusinessExceptionAssert extends IResponseEnum, Assert {
    8. //jdk8以后接口里面可以包含方法体,但必须使用default或static修饰,
    9. // 而且我们知道实现类如果继承了接口,实现类必须强制重现接口的方法,但是这两种方式是不需要强制重写的,相当于没有abstract修饰
    10. @Override
    11. default BaseException newException(Object... args) {
    12. String msg = MessageFormat.format(this.getMessage(), args);
    13. return new BusinessException(this, args, msg);
    14. }
    15. @Override
    16. default BaseException newException(Throwable t, Object... args) {
    17. String msg = MessageFormat.format(this.getMessage(), args);
    18. return new BusinessException(this, args, msg, t);
    19. }
    20. }
    1. package com.XX.edu.common.exception.enums;
    2. import com.XX.edu.common.exception.assertion.BusinessExceptionAssert;
    3. import lombok.AllArgsConstructor;
    4. import lombok.Getter;
    5. /**
    6. *

      业务

    7. */
    8. @Getter
    9. @AllArgsConstructor
    10. public enum BusinessResponseEnum implements BusinessExceptionAssert {
    11. UNCLASSIFIED(5001, "根据课程id={0},班级id={1}未查询到班级信息"),
    12. UNEXERCISEiNFO(5002, "根据习题id={0}未查询到习题详情"),
    13. UNEXERCISE(5003, "习题id={0}不存在"),
    14. DUMPLICATEEXERCISE(5004, "习题ID={0}已在删除状态,不可重复删除"),
    15. CANNOTDELETEEXERCISE(5005, "习题ID={0}正在使用中,不可删除"),
    16. NOMIGRATIONEXERCISE(5006, "没有需要迁移的历史数据"),
    17. ;
    18. /**
    19. * 返回码
    20. */
    21. private int code;
    22. /**
    23. * 返回消息
    24. */
    25. private String message;
    26. }
    1. package com.XX.edu.common.exception.enums;
    2. import com.XX.edu.common.exception.assertion.CommonExceptionAssert;
    3. import lombok.AllArgsConstructor;
    4. import lombok.Getter;
    5. /**
    6. *

      通用返回结果

    7. *
    8. */
    9. @Getter
    10. @AllArgsConstructor
    11. public enum CommonResponseEnum implements CommonExceptionAssert {
    12. /**
    13. * 成功
    14. */
    15. SUCCESS(0, "SUCCESS"),
    16. /**
    17. * 服务器繁忙,请稍后重试
    18. */
    19. SERVER_BUSY(9998, "服务器繁忙"),
    20. /**
    21. * 服务器异常,无法识别的异常,尽可能对通过判断减少未定义异常抛出
    22. */
    23. SERVER_ERROR(9999, "网络异常");
    24. /**
    25. * 返回码
    26. */
    27. private int code;
    28. /**
    29. * 返回消息
    30. */
    31. private String message;
    32. }

     

    1. package com.XX.edu.common.exception.enums;
    2. import com.XX.edu.common.exception.assertion.CommonExceptionAssert;
    3. import lombok.AllArgsConstructor;
    4. import lombok.Getter;
    5. /**
    6. *

      参数校验异常返回结果

    7. *
    8. * @author sprainkle
    9. * @date 2019/5/2
    10. */
    11. @Getter
    12. @AllArgsConstructor
    13. public enum ArgumentResponseEnum implements CommonExceptionAssert {
    14. /**
    15. * 绑定参数校验异常
    16. */
    17. VALID_ERROR(6000, "参数校验异常");
    18. /**
    19. * 返回码
    20. */
    21. private int code;
    22. /**
    23. * 返回消息
    24. */
    25. private String message;
    26. }
    1. package com.XX.edu.common.exception.enums;
    2. import lombok.AllArgsConstructor;
    3. import lombok.Getter;
    4. import javax.servlet.http.HttpServletResponse;
    5. /**
    6. *

      异常类与http status对照关系

    7. *
    8. * @author
    9. * @date 2022/11/1
    10. * @see org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
    11. */
    12. @Getter
    13. @AllArgsConstructor
    14. public enum ServletResponseEnum {
    15. MethodArgumentNotValidException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
    16. MethodArgumentTypeMismatchException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
    17. MissingServletRequestPartException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
    18. MissingPathVariableException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
    19. BindException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
    20. MissingServletRequestParameterException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
    21. TypeMismatchException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
    22. ServletRequestBindingException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
    23. HttpMessageNotReadableException(4400, "", HttpServletResponse.SC_BAD_REQUEST),
    24. NoHandlerFoundException(4404, "", HttpServletResponse.SC_NOT_FOUND),
    25. NoSuchRequestHandlingMethodException(4404, "", HttpServletResponse.SC_NOT_FOUND),
    26. HttpRequestMethodNotSupportedException(4405, "", HttpServletResponse.SC_METHOD_NOT_ALLOWED),
    27. HttpMediaTypeNotAcceptableException(4406, "", HttpServletResponse.SC_NOT_ACCEPTABLE),
    28. HttpMediaTypeNotSupportedException(4415, "", HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE),
    29. ConversionNotSupportedException(4500, "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
    30. HttpMessageNotWritableException(4500, "", HttpServletResponse.SC_INTERNAL_SERVER_ERROR),
    31. AsyncRequestTimeoutException(4503, "", HttpServletResponse.SC_SERVICE_UNAVAILABLE)
    32. ;
    33. /**
    34. * 返回码,目前与{@link #statusCode}相同
    35. */
    36. private int code;
    37. /**
    38. * 返回信息,直接读取异常的message
    39. */
    40. private String message;
    41. /**
    42. * HTTP状态码
    43. */
    44. private int statusCode;
    45. }

     

    1. package com.XX.edu.common.exception;
    2. import com.XX.edu.common.exception.enums.IResponseEnum;
    3. import lombok.Getter;
    4. /**
    5. * @Description: 异常基类
    6. * @Title: BaseException
    7. * @Package com.XX.edu.common.exception
    8. * @Author:
    9. * @Copyright
    10. * @CreateTime: 2022/11/1 13:43
    11. */
    12. @Getter
    13. public class BaseException extends RuntimeException {
    14. private static final long serialVersionUID = 1L;
    15. /**
    16. * 返回码
    17. */
    18. protected IResponseEnum responseEnum;
    19. /**
    20. * 异常消息参数
    21. */
    22. protected Object[] args;
    23. public BaseException(IResponseEnum responseEnum) {
    24. super(responseEnum.getMessage());
    25. this.responseEnum = responseEnum;
    26. }
    27. public BaseException(int code, String msg) {
    28. super(msg);
    29. this.responseEnum = new IResponseEnum() {
    30. @Override
    31. public int getCode() {
    32. return code;
    33. }
    34. @Override
    35. public String getMessage() {
    36. return msg;
    37. }
    38. };
    39. }
    40. public BaseException(IResponseEnum responseEnum, Object[] args, String message) {
    41. super(message);
    42. this.responseEnum = responseEnum;
    43. this.args = args;
    44. }
    45. public BaseException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
    46. super(message, cause);
    47. this.responseEnum = responseEnum;
    48. this.args = args;
    49. }
    50. }
    1. package com.XX.edu.common.exception;
    2. import com.XX.edu.common.exception.enums.IResponseEnum;
    3. /**
    4. *

      参数异常

    5. *

      在处理业务过程中校验参数出现错误, 可以抛出该异常

    6. *

      编写公共代码(如工具类)时,对传入参数检查不通过时,可以抛出该异常

    7. *
    8. */
    9. public class ArgumentException extends BaseException {
    10. private static final long serialVersionUID = 1L;
    11. public ArgumentException(IResponseEnum responseEnum, Object[] args, String message) {
    12. super(responseEnum, args, message);
    13. }
    14. public ArgumentException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
    15. super(responseEnum, args, message, cause);
    16. }
    17. }

     

    1. package com.XX.edu.common.exception;
    2. import com.XX.edu.common.exception.enums.IResponseEnum;
    3. /**
    4. * @Description: 业务异常,业务处理时,出现异常,可以抛出该异常
    5. * @Title: BusinessException
    6. * @Package com.XX.edu.common.exception
    7. * @Author:
    8. * @Copyright
    9. * @CreateTime: 2022/11/1 13:32
    10. */
    11. public class BusinessException extends BaseException {
    12. private static final long serialVersionUID = 1L;
    13. public BusinessException(IResponseEnum responseEnum, Object[] args, String message) {
    14. super(responseEnum, args, message);
    15. }
    16. public BusinessException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
    17. super(responseEnum, args, message, cause);
    18. }
    19. }
    1. package com.XX.edu.common.exception.i18n;
    2. import org.springframework.context.MessageSource;
    3. import org.springframework.context.i18n.LocaleContextHolder;
    4. import org.springframework.stereotype.Service;
    5. import javax.annotation.Resource;
    6. import java.util.Locale;
    7. @Service
    8. public class UnifiedMessageSource {
    9. @Resource
    10. private MessageSource messageSource;
    11. /**
    12. * 获取国际化消息
    13. * @param code 消息code
    14. * @return
    15. */
    16. public String getMessage(String code) {
    17. return getMessage(code, null);
    18. }
    19. /**
    20. * 获取国际化消息
    21. * @param code 消息code
    22. * @param args 参数
    23. * @return
    24. */
    25. public String getMessage(String code, Object[] args) {
    26. return getMessage(code, args, "");
    27. }
    28. /**
    29. * 获取国际化消息
    30. * @param code 消息code
    31. * @param args 参数
    32. * @param defaultMessage 默认消息
    33. * @return
    34. */
    35. public String getMessage(String code, Object[] args, String defaultMessage) {
    36. Locale locale = LocaleContextHolder.getLocale();
    37. return messageSource.getMessage(code, args, defaultMessage, locale);
    38. }
    39. }

     使用枚举类结合(继承)Assert,只需根据特定的异常情况定义不同的枚举实例,就能够针对不同情况抛出特定的异常(这里指携带特定的异常码和异常消息),这样既不用定义大量的异常类,同时还具备了断言的良好可读性。 

    使用:

     

    全局异常处理

    实际上异常只有两大类,一类是ServletException、ServiceException,还记得上文提到的 按阶段分类 吗,即对应 进入Controller前的异常 和 Service 层异常;然后 ServiceException 再分成自定义异常、未知异常。对应关系如下: 进入Controller前的异常: handleServletException、handleBindException、handleValidException 自定义异常: handleBusinessException、handleBaseException 未知异常: handleException

    下面我们来看一下全局异常如何处理

    1. package com.XX.edu.common.exception.handler;
    2. /**
    3. * @Description: 定义统一异常处理器类
    4. * @Title: UnifiedExceptionHandler
    5. * @Package com.XX.edu.common.exception
    6. * @Author:
    7. * @Copyright
    8. * @CreateTime: 2022/11/1 14:02
    9. */
    10. import com.XX.edu.common.bean.ResultTO;
    11. import com.XX.edu.common.exception.BaseException;
    12. import com.XX.edu.common.exception.BusinessException;
    13. import com.XX.edu.common.exception.enums.ArgumentResponseEnum;
    14. import com.XX.edu.common.exception.enums.CommonResponseEnum;
    15. import com.XX.edu.common.exception.enums.ServletResponseEnum;
    16. import com.XX.edu.common.exception.i18n.UnifiedMessageSource;
    17. import org.slf4j.Logger;
    18. import org.slf4j.LoggerFactory;
    19. import org.springframework.beans.ConversionNotSupportedException;
    20. import org.springframework.beans.TypeMismatchException;
    21. import org.springframework.beans.factory.annotation.Autowired;
    22. import org.springframework.beans.factory.annotation.Value;
    23. import org.springframework.http.converter.HttpMessageNotReadableException;
    24. import org.springframework.http.converter.HttpMessageNotWritableException;
    25. import org.springframework.validation.BindException;
    26. import org.springframework.validation.BindingResult;
    27. import org.springframework.validation.FieldError;
    28. import org.springframework.validation.ObjectError;
    29. import org.springframework.web.HttpMediaTypeNotAcceptableException;
    30. import org.springframework.web.HttpMediaTypeNotSupportedException;
    31. import org.springframework.web.HttpRequestMethodNotSupportedException;
    32. import org.springframework.web.bind.MethodArgumentNotValidException;
    33. import org.springframework.web.bind.MissingPathVariableException;
    34. import org.springframework.web.bind.MissingServletRequestParameterException;
    35. import org.springframework.web.bind.ServletRequestBindingException;
    36. import org.springframework.web.bind.annotation.ExceptionHandler;
    37. import org.springframework.web.bind.annotation.RestControllerAdvice;
    38. import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
    39. import org.springframework.web.multipart.support.MissingServletRequestPartException;
    40. import org.springframework.web.servlet.NoHandlerFoundException;
    41. /**
    42. *

      全局异常处理器

    43. */
    44. @RestControllerAdvice
    45. public class UnifiedExceptionHandler {
    46. Logger logger = LoggerFactory.getLogger(getClass());
    47. /**
    48. * 生产环境BusinessException
    49. */
    50. private final static String ENV_PROD = "prod";
    51. @Autowired
    52. private UnifiedMessageSource unifiedMessageSource;
    53. /**
    54. * 当前环境
    55. */
    56. @Value("${spring.profiles.active}")
    57. private String profile;
    58. /**
    59. * 自定义异常
    60. *

    61. * BaseException extends RuntimeException
    62. *
    63. * @param e 异常
    64. * @return 异常结果
    65. */
    66. @ExceptionHandler(value = BaseException.class)
    67. public ResultTO handleBaseException(BaseException e) {
    68. logger.error(e.getMessage(), e);
    69. return ResultTO.FAILURE(getMessage(e), e.getResponseEnum().getCode());
    70. }
    71. /**
    72. * 未定义异常
    73. *
    74. * @param e 异常
    75. * @return 异常结果
    76. */
    77. @ExceptionHandler(value = Exception.class)
    78. public ResultTO handleException(Exception e) {
    79. logger.error(e.getMessage(), e);
    80. if (ENV_PROD.equals(profile)) {
    81. // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如数据库异常信息.
    82. int code = CommonResponseEnum.SERVER_ERROR.getCode();
    83. BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR);
    84. String message = getMessage(baseException);
    85. return ResultTO.FAILURE(message, code);
    86. }
    87. return ResultTO.FAILURE(e.getMessage(), CommonResponseEnum.SERVER_ERROR.getCode());
    88. }
    89. /**
    90. * 业务异常
    91. *
    92. * @param e 异常
    93. * @return 异常结果
    94. */
    95. @ExceptionHandler(value = BusinessException.class)
    96. public ResultTO handleBusinessException(BaseException e) {
    97. logger.error(e.getMessage(), e);
    98. return ResultTO.FAILURE(getMessage(e),e.getResponseEnum().getCode());
    99. }
    100. /**
    101. * Controller上一层相关异常
    102. *
    103. * @param e 异常
    104. * @return 异常结果
    105. */
    106. @ExceptionHandler({
    107. NoHandlerFoundException.class,
    108. HttpRequestMethodNotSupportedException.class,
    109. HttpMediaTypeNotSupportedException.class,
    110. HttpMediaTypeNotAcceptableException.class,
    111. MissingPathVariableException.class,
    112. MissingServletRequestParameterException.class,
    113. TypeMismatchException.class,
    114. HttpMessageNotReadableException.class,
    115. HttpMessageNotWritableException.class,
    116. // BindException.class,
    117. // MethodArgumentNotValidException.class
    118. ServletRequestBindingException.class,
    119. ConversionNotSupportedException.class,
    120. MissingServletRequestPartException.class,
    121. AsyncRequestTimeoutException.class
    122. })
    123. public ResultTO handleServletException(Exception e) {
    124. logger.error(e.getMessage(), e);
    125. int code = CommonResponseEnum.SERVER_ERROR.getCode();
    126. try {
    127. ServletResponseEnum servletExceptionEnum = ServletResponseEnum.valueOf(e.getClass().getSimpleName());
    128. code = servletExceptionEnum.getCode();
    129. } catch (IllegalArgumentException e1) {
    130. logger.error("class [{}] not defined in enum {}", e.getClass().getName(), ServletResponseEnum.class.getName());
    131. }
    132. if (ENV_PROD.equals(profile)) {
    133. // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如404.
    134. code = CommonResponseEnum.SERVER_ERROR.getCode();
    135. BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR);
    136. String message = getMessage(baseException);
    137. return ResultTO.FAILURE(message, code);
    138. }
    139. return ResultTO.FAILURE(e.getMessage(), code);
    140. }
    141. /**
    142. * 参数绑定异常
    143. *
    144. * @param e 异常
    145. * @return 异常结果
    146. */
    147. @ExceptionHandler(value = BindException.class)
    148. public ResultTO handleBindException(BindException e) {
    149. logger.error("参数绑定校验异常", e);
    150. return wrapperBindingResult(e.getBindingResult());
    151. }
    152. /**
    153. * 参数校验(Valid)异常,将校验失败的所有异常组合成一条错误信息
    154. *
    155. * @param e 异常
    156. * @return 异常结果
    157. */
    158. @ExceptionHandler(value = MethodArgumentNotValidException.class)
    159. public ResultTO handleValidException(MethodArgumentNotValidException e) {
    160. logger.error("参数绑定校验异常", e);
    161. return wrapperBindingResult(e.getBindingResult());
    162. }
    163. /**
    164. * 包装绑定异常结果
    165. *
    166. * @param bindingResult 绑定结果
    167. * @return 异常结果
    168. */
    169. private ResultTO wrapperBindingResult(BindingResult bindingResult) {
    170. StringBuilder msg = new StringBuilder();
    171. for (ObjectError error : bindingResult.getAllErrors()) {
    172. msg.append(", ");
    173. if (error instanceof FieldError) {
    174. msg.append(((FieldError) error).getField()).append(": ");
    175. }
    176. msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
    177. }
    178. return ResultTO.FAILURE(msg.substring(2), ArgumentResponseEnum.VALID_ERROR.getCode());
    179. }
    180. /**
    181. * 获取国际化消息
    182. *
    183. * @param e 异常
    184. * @return
    185. */
    186. public String getMessage(BaseException e) {
    187. String code = "response." + e.getResponseEnum().toString();
    188. String message = unifiedMessageSource.getMessage(code, e.getArgs());
    189. if (message == null || message.isEmpty()) {
    190. return e.getMessage();
    191. }
    192. return message;
    193. }
    194. }

    这样项目抛出的异常就会到异常处理类中统一处理~~

    收工~!!

  • 相关阅读:
    十三、SpringBoot错误处理底层组件和异常处理流程分析
    GPU是什么?GPU有多重要?
    JavaScript 数据结构与算法3(链表)
    第二章《Java程序世界初探》第2节:常量的使用
    C++ 学习 之 成员指针
    基于web的医疗设备销售业务系统的设计与实现
    2022 ICPC Gran Premio de Mexico 1ra Fecha (B、D、E、F)
    Endnote 中批量导出PDF
    【LeetCode】2651.计算列车到站时间
    【虹科】物联网时代,加个网关or加个软件,设备上云原来如此简单
  • 原文地址:https://blog.csdn.net/feixiangdexiaozhidan/article/details/127689767