• 为什么不建议用try catch处理异常?


    来自:简书,作者:sprinkle_liz

    链接:https://www.jianshu.com/p/3f3d9e8d1efa

    软件开发过程中,不可避免的是需要处理各种异常,就我自己来说,至少有一半以上的时间都是在处理各种异常情况,所以代码中就会出现大量的 try {...} catch {...} finally {...} 代码块,不仅有大量的冗余代码,而且还影响代码的可读性。

    比较下面两张图,看看您现在编写的代码属于哪一种风格?然后哪种编码风格您更喜欢?

    丑陋的 try catch 代码块:

    96a2fb9e2ccc330062502a5a35916ca1.png

    优雅的 Controller:

    2447a2d728d9bbb9cc079d960713be96.png

    上面的示例,还只是在 Controller 层,如果是在 Service 层,可能会有更多的 try catch 代码块。这将会严重影响代码的可读性、“美观性”。

    所以如果是我的话,我肯定偏向于第二种,我可以把更多的精力放在业务代码的开发,同时代码也会变得更加简洁。

    既然业务代码不显式地对异常进行捕获、处理,而异常肯定还是处理的,不然系统岂不是动不动就崩溃了,所以必须得有其他地方捕获并处理这些异常。

    那么问题来了,如何优雅的处理各种异常?

    什么是统一异常处理

    Spring 在 3.2 版本增加了一个注解 @ControllerAdvice,可以与 @ExceptionHandler、@InitBinder、@ModelAttribute 等注解注解配套使用。

    对于这几个注解的作用,这里不做过多赘述,若有不了解的,可以参考 Spring 3.2 新注解 @ControllerAdvice,先大概有个了解。

    不过跟异常处理相关的只有注解 @ExceptionHandler,从字面上看,就是异常处理器的意思。

    其实际作用也是:若在某个 Controller 类定义一个异常处理方法,并在方法上添加该注解,那么当出现指定的异常时,会执行该处理异常的方法。

    其可以使用 SpringMVC 提供的数据绑定,比如注入 HttpServletRequest 等,还可以接受一个当前抛出的 Throwable 对象。

    但是,这样一来,就必须在每一个 Controller 类都定义一套这样的异常处理方法,因为异常可以是各种各样。这样一来,就会造成大量的冗余代码,而且若需要新增一种异常的处理逻辑,就必须修改所有 Controller 类了,很不优雅。

    当然你可能会说,那就定义个类似 BaseController 的基类,这样总行了吧。

    这种做法虽然没错,但仍不尽善尽美,因为这样的代码有一定的侵入性和耦合性。简简单单的 Controller,我为啥非得继承这样一个类呢,万一已经继承其他基类了呢。大家都知道 Java 只能继承一个类。

    那有没有一种方案,既不需要跟 Controller 耦合,也可以将定义的异常处理器应用到所有控制器呢?

    所以注解 @ControllerAdvice 出现了,简单的说,该注解可以把异常处理器应用到所有控制器,而不是单个控制器。

    借助该注解,我们可以实现:在独立的某个地方,比如单独一个类,定义一套对各种异常的处理机制,然后在类的签名加上注解 @ControllerAdvice,统一对不同阶段的、不同异常进行处理。这就是统一异常处理的原理。

    注意到上面对异常按阶段进行分类,大体可以分成:进入 Controller 前的异常和 Service 层异常。

    具体可以参考下图:

    dc40ef8ee23c6a12eabc5776cb2976ca.png

    不同阶段的异常

    目标

    消灭 95% 以上的 try catch 代码块,以优雅的 Assert(断言)方式来校验业务的异常情况,只关注业务逻辑,而不用花费大量精力写冗余的 try catch 代码块。

    统一异常处理实战

    在定义统一异常处理类之前,先来介绍一下如何优雅的判定异常情况并抛异常。

    | 用 Assert(断言)替换 throw exception

    想必 Assert(断言)大家都很熟悉,比如 Spring 家族的 org.springframework.util.Assert,在我们写测试用例的时候经常会用到。

    使用断言能让我们编码的时候有一种非一般丝滑的感觉,比如:

    1. @Test
    2.     public void test1() {
    3.         ...
    4.         User user = userDao.selectById(userId);
    5.         Assert.notNull(user, "用户不存在.");
    6.         ...
    7.     }
    8.     @Test
    9.     public void test2() {
    10.         // 另一种写法
    11.         User user = userDao.selectById(userId);
    12.         if (user == null) {
    13.             throw new IllegalArgumentException("用户不存在.");
    14.         }
    15.     }

    有没有感觉第一种判定非空的写法很优雅,第二种写法则是相对丑陋的 if {...} 代码块。那么神奇的 Assert.notNull() 背后到底做了什么呢?

    下面是 Assert 的部分源码:

    1. public abstract class Assert {
    2.     public Assert() {
    3.     }
    4.     public static void notNull(@Nullable Object object, String message) {
    5.         if (object == null) {
    6.             throw new IllegalArgumentException(message);
    7.         }
    8.     }
    9. }

    可以看到,Assert 其实就是帮我们把 if {...} 封装了一下,是不是很神奇?虽然很简单,但不可否认的是编码体验至少提升了一个档次。

    那么我们能不能模仿 org.springframework.util.Assert,也写一个断言类,不过断言失败后抛出的异常不是 IllegalArgumentException 这些内置异常,而是我们自己定义的异常。

    下面让我们来尝试一下:

    1. Assert
    2. public interface Assert {
    3.     /**
    4.      * 创建异常
    5.      * @param args
    6.      * @return
    7.      */
    8.     BaseException newException(Object... args);
    9.     /**
    10.      * 创建异常
    11.      * @param t
    12.      * @param args
    13.      * @return
    14.      */
    15.     BaseException newException(Throwable t, Object... args);
    16.     /**
    17.      * <p>断言对象<code>obj</code>非空。如果对象<code>obj</code>为空,则抛出异常
    18.      *
    19.      * @param obj 待判断对象
    20.      */
    21.     default void assertNotNull(Object obj) {
    22.         if (obj == null) {
    23.             throw newException(obj);
    24.         }
    25.     }
    26.     /**
    27.      * <p>断言对象<code>obj</code>非空。如果对象<code>obj</code>为空,则抛出异常
    28.      * <p>异常信息<code>message</code>支持传递参数方式,避免在判断之前进行字符串拼接操作
    29.      *
    30.      * @param obj 待判断对象
    31.      * @param args message占位符对应的参数列表
    32.      */
    33.     default void assertNotNull(Object obj, Object... args) {
    34.         if (obj == null) {
    35.             throw newException(args);
    36.         }
    37.     }
    38. }

    上面的 Assert 断言方法是使用接口的默认方法定义的,然后有没有发现当断言失败后,抛出的异常不是具体的某个异常,而是交由 2 个 newException 接口方法提供。

    因为业务逻辑中出现的异常基本都是对应特定的场景,比如根据用户 id 获取用户信息,查询结果为 null,此时抛出的异常可能为 UserNotFoundException,并且有特定的异常码(比如 7001)和异常信息“用户不存在”。

    所以具体抛出什么异常,由 Assert 的实现类决定。

    看到这里,您可能会有这样的疑问,按照上面的说法,那岂不是有多少异常情况,就得有定义等量的断言类和异常类,这显然是反人类的,这也没想象中高明嘛。别急,且听我细细道来。

    | 善解人意的 Enum

    自定义异常 BaseException 有 2 个属性,即 code、message,这样一对属性,有没有想到什么类一般也会定义这 2 个属性?

    没错,就是枚举类。且看我如何将 Enum 和 Assert 结合起来,相信我一定会让你眼前一亮。

    如下:

    1. public interface IResponseEnum {
    2.     int getCode();
    3.     String getMessage();
    4. }
    5. /**
    6.  * <p>业务异常</p>
    7.  * <p>业务处理时,出现异常,可以抛出该异常</p>
    8.  */
    9. public class BusinessException extends  BaseException {
    10.     private static final long serialVersionUID = 1L;
    11.     public BusinessException(IResponseEnum responseEnum, Object[] args, String message) {
    12.         super(responseEnum, args, message);
    13.     }
    14.     public BusinessException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) {
    15.         super(responseEnum, args, message, cause);
    16.     }
    17. }
    18. public interface BusinessExceptionAssert extends IResponseEnum, Assert {
    19.     @Override
    20.     default BaseException newException(Object... args) {
    21.         String msg = MessageFormat.format(this.getMessage(), args);
    22.         return new BusinessException(this, args, msg);
    23.     }
    24.     @Override
    25.     default BaseException newException(Throwable t, Object... args) {
    26.         String msg = MessageFormat.format(this.getMessage(), args);
    27.         return new BusinessException(this, args, msg, t);
    28.     }
    29. }
    30. @Getter
    31. @AllArgsConstructor
    32. public enum ResponseEnum implements BusinessExceptionAssert {
    33.     /**
    34.      * Bad licence type
    35.      */
    36.     BAD_LICENCE_TYPE(7001"Bad licence type."),
    37.     /**
    38.      * Licence not found
    39.      */
    40.     LICENCE_NOT_FOUND(7002"Licence not found.")
    41.     ;
    42.     /**
    43.      * 返回码
    44.      */
    45.     private int code;
    46.     /**
    47.      * 返回消息
    48.      */
    49.     private String message;
    50. }

    看到这里,有没有眼前一亮的感觉,代码示例中定义了两个枚举实例:

    • BAD_LICENCE_TYPE

    • LICENCE_NOT_FOUND

    他们分别对应了 BadLicenceTypeException、LicenceNotFoundException 两种异常。

    以后每增加一种异常情况,只需增加一个枚举实例即可,再也不用每一种异常都定义一个异常类了。然后再来看下如何使用,假设 LicenceService 有校验 Licence 是否存在的方法,如下:

    1. /**
    2.      * 校验{@link Licence}存在
    3.      * @param licence
    4.      */
    5.     private void checkNotNull(Licence licence) {
    6.         ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence);
    7.     }

    若不使用断言,代码可能如下:

    1. private void checkNotNull(Licence licence) {
    2.         if (licence == null) {
    3.             throw new LicenceNotFoundException();
    4.             // 或者这样
    5.             throw new BusinessException(7001"Bad licence type.");
    6.         }
    7.     }

    使用枚举类结合(继承)Assert,只需根据特定的异常情况定义不同的枚举实例,如上面的 BAD_LICENCE_TYPE、LICENCE_NOT_FOUND,就能够针对不同情况抛出特定的异常(这里指携带特定的异常码和异常消息)。

    这样既不用定义大量的异常类,同时还具备了断言的良好可读性,当然这种方案的好处远不止这些,请继续阅读后文,慢慢体会。

    注:上面举的例子是针对特定的业务,而有部分异常情况是通用的,比如:服务器繁忙、网络异常、服务器异常、参数校验异常、404 等,所以有CommonResponseEnum、ArgumentResponseEnum、ServletResponseEnum,其中 ServletResponseEnum 会在后文详细说明。

    | 定义统一异常处理器类

    1. @Slf4j
    2. @Component
    3. @ControllerAdvice
    4. @ConditionalOnWebApplication
    5. @ConditionalOnMissingBean(UnifiedExceptionHandler.class)
    6. public class UnifiedExceptionHandler {
    7.     /**
    8.      * 生产环境
    9.      */
    10.     private final static String ENV_PROD = "prod";
    11.     @Autowired
    12.     private UnifiedMessageSource unifiedMessageSource;
    13.     /**
    14.      * 当前环境
    15.      */
    16.     @Value("${spring.profiles.active}")
    17.     private String profile;
    18.     /**
    19.      * 获取国际化消息
    20.      *
    21.      * @param e 异常
    22.      * @return
    23.      */
    24.     public String getMessage(BaseException e) {
    25.         String code = "response." + e.getResponseEnum().toString();
    26.         String message = unifiedMessageSource.getMessage(code, e.getArgs());
    27.         if (message == null || message.isEmpty()) {
    28.             return e.getMessage();
    29.         }
    30.         return message;
    31.     }
    32.     /**
    33.      * 业务异常
    34.      *
    35.      * @param e 异常
    36.      * @return 异常结果
    37.      */
    38.     @ExceptionHandler(value = BusinessException.class)
    39.     @ResponseBody
    40.     public ErrorResponse handleBusinessException(BaseException e) {
    41.         log.error(e.getMessage(), e);
    42.         return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e));
    43.     }
    44.     /**
    45.      * 自定义异常
    46.      *
    47.      * @param e 异常
    48.      * @return 异常结果
    49.      */
    50.     @ExceptionHandler(value = BaseException.class)
    51.     @ResponseBody
    52.     public ErrorResponse handleBaseException(BaseException e) {
    53.         log.error(e.getMessage(), e);
    54.         return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e));
    55.     }
    56.     /**
    57.      * Controller上一层相关异常
    58.      *
    59.      * @param e 异常
    60.      * @return 异常结果
    61.      */
    62.     @ExceptionHandler({
    63.             NoHandlerFoundException.class,
    64.             HttpRequestMethodNotSupportedException.class,
    65.             HttpMediaTypeNotSupportedException.class,
    66.             MissingPathVariableException.class,
    67.             MissingServletRequestParameterException.class,
    68.             TypeMismatchException.class,
    69.             HttpMessageNotReadableException.class,
    70.             HttpMessageNotWritableException.class,
    71.             // BindException.class,
    72.             // MethodArgumentNotValidException.class
    73.             HttpMediaTypeNotAcceptableException.class,
    74.             ServletRequestBindingException.class,
    75.             ConversionNotSupportedException.class,
    76.             MissingServletRequestPartException.class,
    77.             AsyncRequestTimeoutException.class
    78.     })
    79.     @ResponseBody
    80.     public ErrorResponse handleServletException(Exception e) {
    81.         log.error(e.getMessage(), e);
    82.         int code = CommonResponseEnum.SERVER_ERROR.getCode();
    83.         try {
    84.             ServletResponseEnum servletExceptionEnum = ServletResponseEnum.valueOf(e.getClass().getSimpleName());
    85.             code = servletExceptionEnum.getCode();
    86.         } catch (IllegalArgumentException e1) {
    87.             log.error("class [{}] not defined in enum {}", e.getClass().getName(), ServletResponseEnum.class.getName());
    88.         }
    89.         if (ENV_PROD.equals(profile)) {
    90.             // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如404.
    91.             code = CommonResponseEnum.SERVER_ERROR.getCode();
    92.             BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR);
    93.             String message = getMessage(baseException);
    94.             return new ErrorResponse(code, message);
    95.         }
    96.         return new ErrorResponse(code, e.getMessage());
    97.     }
    98.     /**
    99.      * 参数绑定异常
    100.      *
    101.      * @param e 异常
    102.      * @return 异常结果
    103.      */
    104.     @ExceptionHandler(value = BindException.class)
    105.     @ResponseBody
    106.     public ErrorResponse handleBindException(BindException e) {
    107.         log.error("参数绑定校验异常", e);
    108.         return wrapperBindingResult(e.getBindingResult());
    109.     }
    110.     /**
    111.      * 参数校验异常,将校验失败的所有异常组合成一条错误信息
    112.      *
    113.      * @param e 异常
    114.      * @return 异常结果
    115.      */
    116.     @ExceptionHandler(value = MethodArgumentNotValidException.class)
    117.     @ResponseBody
    118.     public ErrorResponse handleValidException(MethodArgumentNotValidException e) {
    119.         log.error("参数绑定校验异常", e);
    120.         return wrapperBindingResult(e.getBindingResult());
    121.     }
    122.     /**
    123.      * 包装绑定异常结果
    124.      *
    125.      * @param bindingResult 绑定结果
    126.      * @return 异常结果
    127.      */
    128.     private ErrorResponse wrapperBindingResult(BindingResult bindingResult) {
    129.         StringBuilder msg = new StringBuilder();
    130.         for (ObjectError error : bindingResult.getAllErrors()) {
    131.             msg.append(", ");
    132.             if (error instanceof FieldError) {
    133.                 msg.append(((FieldError) error).getField()).append(": ");
    134.             }
    135.             msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage());
    136.         }
    137.         return new ErrorResponse(ArgumentResponseEnum.VALID_ERROR.getCode(), msg.substring(2));
    138.     }
    139.     /**
    140.      * 未定义异常
    141.      *
    142.      * @param e 异常
    143.      * @return 异常结果
    144.      */
    145.     @ExceptionHandler(value = Exception.class)
    146.     @ResponseBody
    147.     public ErrorResponse handleException(Exception e) {
    148.         log.error(e.getMessage(), e);
    149.         if (ENV_PROD.equals(profile)) {
    150.             // 当为生产环境, 不适合把具体的异常信息展示给用户, 比如数据库异常信息.
    151.             int code = CommonResponseEnum.SERVER_ERROR.getCode();
    152.             BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR);
    153.             String message = getMessage(baseException);
    154.             return new ErrorResponse(code, message);
    155.         }
    156.         return new ErrorResponse(CommonResponseEnum.SERVER_ERROR.getCode(), e.getMessage());
    157.     }
    158. }

    可以看到,上面将异常分成几类,实际上只有两大类,一类是 ServletException、ServiceException。

    还记得上文提到的按阶段分类吗,即对应进入 Controller 前的异常 和 Service 层异常;然后 ServiceException 再分成自定义异常、未知异常。

    对应关系如下:

    • 进入 Controller 前的异常:handleServletException、handleBindException、handleValidException

    • 自定义异常:handleBusinessException、handleBaseException

    • 未知异常:handleException

    接下来分别对这几种异常处理器做详细说明。

    异常处理器说明

    | handleServletException

    一个 http 请求,在到达 Controller 前,会对该请求的请求信息与目标控制器信息做一系列校验。

    这里简单说一下:

    NoHandlerFoundException:首先根据请求 Url 查找有没有对应的控制器,若没有则会抛该异常,也就是大家非常熟悉的 404 异常。

    HttpRequestMethodNotSupportedException:若匹配到了(匹配结果是一个列表,不同的是 http 方法不同,如:Get、Post 等),则尝试将请求的 http 方法与列表的控制器做匹配,若没有对应 http 方法的控制器,则抛该异常。

    HttpMediaTypeNotSupportedException:然后再对请求头与控制器支持的做比较。

    比如 content-type 请求头,若控制器的参数签名包含注解 @RequestBody,但是请求的 content-type 请求头的值没有包含 application/json,那么会抛该异常(当然,不止这种情况会抛这个异常)。

    MissingPathVariableException:未检测到路径参数。比如 url 为:/licence/{licenceId},参数签名包含 @PathVariable("licenceId")。

    当请求的 url 为 /licence,在没有明确定义 url 为 /licence 的情况下,会被判定为:缺少路径参数。

    MissingServletRequestParameterException:缺少请求参数。比如定义了参数 @RequestParam("licenceId") String licenceId,但发起请求时,未携带该参数,则会抛该异常。

    TypeMismatchException:参数类型匹配失败。比如:接收参数为 Long 型,但传入的值确是一个字符串,那么将会出现类型转换失败的情况,这时会抛该异常。

    HttpMessageNotReadableException:与上面的 HttpMediaTypeNotSupportedException 举的例子完全相反。

    即请求头携带了"content-type: application/json;charset=UTF-8",但接收参数却没有添加注解 @RequestBody,或者请求体携带的 json 串反序列化成 pojo 的过程中失败了,也会抛该异常。

    HttpMessageNotWritableException:返回的 pojo 在序列化成 json 过程失败了,那么抛该异常。

    | handleBindException

    参数校验异常,后文详细说明。

    | handleValidException

    参数校验异常,后文详细说明。

    | handleBusinessException、handleBaseException

    处理自定义的业务异常,只是 handleBaseException 处理的是除了 BusinessException 意外的所有业务异常。就目前来看,这 2 个是可以合并成一个的。

    | handleException

    处理所有未知的异常,比如操作数据库失败的异常。

    注:上面的 handleServletException、handleException 这两个处理器,返回的异常信息,不同环境返回的可能不一样,以为这些异常信息都是框架自带的异常信息,一般都是英文的,不太好直接展示给用户看,所以统一返回 SERVER_ERROR 代表的异常信息。

    异于常人的404

    上文提到,当请求没有匹配到控制器的情况下,会抛出 NoHandlerFoundException 异常,但其实默认情况下不是这样,默认情况下会出现类似如下页面:

    b1fad78ff70cf4832f6d8a1f3bcb0ea3.png

    Whitelabel Error Page

    这个页面是如何出现的呢?实际上,当出现 404 的时候,默认是不抛异常的,而是 forward 跳转到 /error 控制器。

    Spring 也提供了默认的 error 控制器,如下:

    a6201fea5ddb246a566597367ed6fde5.png

    那么,如何让 404 也抛出异常呢,只需在 properties 文件中加入如下配置即可:

    1. spring.mvc.throw-exception-if-no-handler-found=true
    2. spring.resources.add-mappings=false

    如此,就可以异常处理器中捕获它了,然后前端只要捕获到特定的状态码,立即跳转到 404 页面即可。

    捕获404对应的异常

    | 统一返回结果

    在验证统一异常处理器之前,顺便说一下统一返回结果。说白了,其实是统一一下返回结果的数据结构。

    code、message 是所有返回结果中必有的字段,而当需要返回数据时,则需要另一个字段 data 来表示。

    所以首先定义一个 BaseResponse 来作为所有返回结果的基类;然后定义一个通用返回结果类 CommonResponse,继承 BaseResponse,而且多了字段 data。

    为了区分成功和失败返回结果,于是再定义一个 ErrorResponse。

    最后还有一种常见的返回结果,即返回的数据带有分页信息,因为这种接口比较常见,所以有必要单独定义一个返回结果类 QueryDataResponse。

    该类继承自 CommonResponse,只是把 data 字段的类型限制为 QueryDdata,QueryDdata中定义了分页信息相应的字段,即 totalCount、pageNo、 pageSize、records。

    其中比较常用的只有 CommonResponse 和 QueryDataResponse,但是名字又贼鬼死长,何不定义 2 个名字超简单的类来替代呢?

    于是 R 和 QR 诞生了,以后返回结果的时候只需这样写:new R<>(data)、new QR<>(queryData)。

    所有的返回结果类的定义这里就不贴出来了。

    | 验证统一异常处理

    因为这一套统一异常处理可以说是通用的,所有可以设计成一个 common包,以后每一个新项目/模块只需引入该包即可。所以为了验证,需要新建一个项目,并引入该 common 包。

    下面是用于验证的主要源码:

    1. @Service
    2. public class LicenceService extends ServiceImpl<LicenceMapper, Licence> {
    3.     @Autowired
    4.     private OrganizationClient organizationClient;
    5.     /**
    6.      * 查询{@link Licence} 详情
    7.      * @param licenceId
    8.      * @return
    9.      */
    10.     public LicenceDTO queryDetail(Long licenceId) {
    11.         Licence licence = this.getById(licenceId);
    12.         checkNotNull(licence);
    13.         OrganizationDTO org = ClientUtil.execute(() -> organizationClient.getOrganization(licence.getOrganizationId()));
    14.         return toLicenceDTO(licence, org);
    15.     }
    16.     /**
    17.      * 分页获取
    18.      * @param licenceParam 分页查询参数
    19.      * @return
    20.      */
    21.     public QueryData<SimpleLicenceDTO> getLicences(LicenceParam licenceParam) {
    22.         String licenceType = licenceParam.getLicenceType();
    23.         LicenceTypeEnum licenceTypeEnum = LicenceTypeEnum.parseOfNullable(licenceType);
    24.         // 断言, 非空
    25.         ResponseEnum.BAD_LICENCE_TYPE.assertNotNull(licenceTypeEnum);
    26.         LambdaQueryWrapper<Licence> wrapper = new LambdaQueryWrapper<>();
    27.         wrapper.eq(Licence::getLicenceType, licenceType);
    28.         IPage<Licence> page = this.page(new QueryPage<>(licenceParam), wrapper);
    29.         return new QueryData<>(page, this::toSimpleLicenceDTO);
    30.     }
    31.     /**
    32.      * 新增{@link Licence}
    33.      * @param request 请求体
    34.      * @return
    35.      */
    36.     @Transactional(rollbackFor = Throwable.class)
    37.     public LicenceAddRespData addLicence(LicenceAddRequest request) {
    38.         Licence licence = new Licence();
    39.         licence.setOrganizationId(request.getOrganizationId());
    40.         licence.setLicenceType(request.getLicenceType());
    41.         licence.setProductName(request.getProductName());
    42.         licence.setLicenceMax(request.getLicenceMax());
    43.         licence.setLicenceAllocated(request.getLicenceAllocated());
    44.         licence.setComment(request.getComment());
    45.         this.save(licence);
    46.         return new LicenceAddRespData(licence.getLicenceId());
    47.     }
    48.     /**
    49.      * entity -> simple dto
    50.      * @param licence {@link Licence} entity
    51.      * @return {@link SimpleLicenceDTO}
    52.      */
    53.     private SimpleLicenceDTO toSimpleLicenceDTO(Licence licence) {
    54.         // 省略
    55.     }
    56.     /**
    57.      * entity -> dto
    58.      * @param licence {@link Licence} entity
    59.      * @param org {@link OrganizationDTO}
    60.      * @return {@link LicenceDTO}
    61.      */
    62.     private LicenceDTO toLicenceDTO(Licence licence, OrganizationDTO org) {
    63.         // 省略
    64.     }
    65.     /**
    66.      * 校验{@link Licence}存在
    67.      * @param licence
    68.      */
    69.     private void checkNotNull(Licence licence) {
    70.         ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence);
    71.     }
    72. }

    PS:这里使用的 DAO 框架是 mybatis-plus。

    启动时,自动插入的数据为:

    1. -- licence
    2. INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)
    3. VALUES (11'user','CustomerPro'100,5);
    4. INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)
    5. VALUES (21'user','suitability-plus'200,189);
    6. INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)
    7. VALUES (32'user','HR-PowerSuite'100,4);
    8. INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated)
    9. VALUES (42'core-prod','WildCat Application Gateway'16,16);
    10. -- organizations
    11. INSERT INTO organization (id, name, contact_name, contact_email, contact_phone)
    12. VALUES (1'customer-crm-co''Mark Balster''mark.balster@custcrmco.com''823-555-1212');
    13. INSERT INTO organization (id, name, contact_name, contact_email, contact_phone)
    14. VALUES (2'HR-PowerSuite''Doug Drewry','doug.drewry@hr.com''920-555-1212');

    开始验证

    | 捕获自定义异常

    获取不存在的 licence 详情:http://localhost:10000/licence/5

    成功响应的请求:

    licenceId=1

    检验非空:

    31bcb1e57b082cb5f60d4ff0393c4ef3.png

    捕获 Licence not found 异常:

    b004396a3364b9466b2c8b0154ca33dd.png

    Licence not found:

    c9dabe5937e7caf335e167c8669db5bc.png

    根据不存在的 licence type 获取 licence 列表:http://localhost:10000/licence/list?licenceType=ddd。可选的 licence type 为:user、core-prod 。

    校验非空:

    e958efe0e7f42c76882481fb082ba0a0.png

    捕获 Bad licence type 异常:

    f694c101fe1b21bcda12fdf5c78feabd.png

    Bad licence type:

    391e87bbccdbf9adb2d598f2ef972da8.png

    | 捕获进入 Controller 前的异常

    ①访问不存在的接口:http://localhost:10000/licence/list/ddd

    捕获 404 异常:

    2b288431b334711906e6a31a98464f22.png

    ②http 方法不支持:http://localhost:10000/licence

    PostMapping:

    b0bd69babfa32ea3d776281e0c9f9cc7.png

    捕获 Request method not supported 异常:

    8ea2bd8690bed2a16a4af618325746ab.png

    Request method not supported:

    58f94f25a0d4d9a644e1ad4e6abcc98a.png

    ③校验异常 1:http://localhost:10000/licence/list?licenceType=

    getLicences:

    ff131a9b79f948823b03901c6a29a3e7.png

    LicenceParam:

    8d6554fb04bf207f8cef597c2e99aef3.png

    捕获参数绑定校验异常:

    0bc39730c6eb8f18e84042427f0e5874.png

    licence type cannot be empty:

    12bc1607c54dc133fb7028e6269797c3.png

    ④校验异常 2:post 请求,这里使用 postman 模拟

    addLicence:

    63cdd2694b815ee666ee53a53d26ab2e.png

    LicenceAddRequest:

    da599d85963877367e060cfcf9ecd7c3.png

    请求 url 即结果:

    1bef349705ca59157cabfd99ded6b15d.png

    捕获参数绑定校验异常:

    05fb55f822c56f03ba9d5e34e85cef50.png

    注:因为参数绑定校验异常的异常信息的获取方式与其它异常不一样,所以才把这 2 种情况的异常从进入 Controller 前的异常单独拆出来,下面是异常信息的收集逻辑。

    异常信息的收集:

    9e46c27ceb23f7a7f0100319c0dcc683.png

    | 捕获未知异常

    假设我们现在随便对 Licence 新增一个字段 test,但不修改数据库表结构,然后访问:http://localhost:10000/licence/1。

    增加 test 字段:

    3fd1fe24aff9489c69e8fe5db29a3f07.png

    捕获数据库异常:

    e7f2ca6e4bd07e63ef5215eb91e1d229.png

    Error querying database:

    41edd84273f13925326fb0d572764c1f.png

    小结

    可以看到,测试的异常都能够被捕获,然后以 code、message 的形式返回。

    每一个项目/模块,在定义业务异常的时候,只需定义一个枚举类,然后实现接口 BusinessExceptionAssert,最后为每一种业务异常定义对应的枚举实例即可,而不用定义许多异常类。使用的时候也很方便,用法类似断言。

    扩展

    在生产环境,若捕获到未知异常或者 ServletException,因为都是一长串的异常信息,若直接展示给用户看,显得不够专业,于是,我们可以这样做:当检测到当前环境是生产环境,那么直接返回 "网络异常"。

    生产环境返回“网络异常”:

    594cf4386df9c59e013017519a57f304.png

    可以通过以下方式修改当前环境:

    52837bd0d840a0bed6cd6e224d6cd4b5.png

    总结

    使用断言和枚举类相结合的方式,再配合统一异常处理,基本大部分的异常都能够被捕获。

    为什么说大部分异常,因为当引入 spring cloud security 后,还会有认证/授权异常,网关的服务降级异常、跨模块调用异常、远程调用第三方服务异常等,这些异常的捕获方式与本文介绍的不太一样,不过限于篇幅,这里不做详细说明,以后会有单独的文章介绍。

    另外,当需要考虑国际化的时候,捕获异常后的异常信息一般不能直接返回,需要转换成对应的语言,不过本文已考虑到了这个,获取消息的时候已经做了国际化映射,逻辑如下:

    b7623c53fb95ef7add4777cacb61ca7f.png

    获取国际化消息

    最后总结,全局异常属于老生长谈的话题,希望这次通过手机的项目对大家有点指导性的学习,大家根据实际情况自行修改。

    也可以采用以下的 jsonResult 对象的方式进行处理,也贴出来代码:

    1. @Slf4j
    2. @RestControllerAdvice
    3. public class GlobalExceptionHandler {
    4.     /**
    5.      * 没有登录
    6.      * @param request
    7.      * @param response
    8.      * @param e
    9.      * @return
    10.      */
    11.     @ExceptionHandler(NoLoginException.class)
    12.     public Object noLoginExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e)
    13.     {
    14.         log.error("[GlobalExceptionHandler][noLoginExceptionHandler] exception",e);
    15.         JsonResult jsonResult = new JsonResult();
    16.         jsonResult.setCode(JsonResultCode.NO_LOGIN);
    17.         jsonResult.setMessage("用户登录失效或者登录超时,请先登录");
    18.         return jsonResult;
    19.     }
    20.     /**
    21.      * 业务异常
    22.      * @param request
    23.      * @param response
    24.      * @param e
    25.      * @return
    26.      */
    27.     @ExceptionHandler(ServiceException.class)
    28.     public Object businessExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e)
    29.     {
    30.         log.error("[GlobalExceptionHandler][businessExceptionHandler] exception",e);
    31.         JsonResult jsonResult = new JsonResult();
    32.         jsonResult.setCode(JsonResultCode.FAILURE);
    33.         jsonResult.setMessage("业务异常,请联系管理员");
    34.         return jsonResult;
    35.     }
    36.     /**
    37.      * 全局异常处理
    38.      * @param request
    39.      * @param response
    40.      * @param e
    41.      * @return
    42.      */
    43.     @ExceptionHandler(Exception.class)
    44.     public Object exceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e)
    45.     {
    46.         log.error("[GlobalExceptionHandler][exceptionHandler] exception",e);
    47.         JsonResult jsonResult = new JsonResult();
    48.         jsonResult.setCode(JsonResultCode.FAILURE);
    49.         jsonResult.setMessage("系统错误,请联系管理员");
    50.         return jsonResult;
    51.     }
    52. }
    --- EOF ---

    推荐↓↓↓

    来源:https://itsoku.blog.csdn.net/article/details/123887539
  • 相关阅读:
    WINDOWS API ——GETFILETIME——获取文件时间
    lua 源码分析之线程对象lua_State
    GPL、BSD、MIT、Mozilla、Apache、LGPL开源协议介绍
    BOOST 线程完全攻略
    宏定义中#和##符号的使用和宏定义展开问题
    weak_ptr<T>智能指针
    轻松记住大端小端的含义(附对大端和小端的解释)
    关于VC预定义常量_WIN32,WIN32,_WIN64
    VC 预定义宏
    php技术之路
  • 原文地址:https://www.cnblogs.com/konglxblog/p/16456819.html
Copyright © 2020-2023  润新知