背景html
软件开发过程当中,不可避免的是须要处理各类异常,就我本身来讲,至少有一半以上的时间都是在处理各类异常状况,因此代码中就会出现大量的try {…} catch {…} finally {…} 代码块,不只有大量的冗余代码,并且还影响代码的可读性。比较下面两张图,看看您如今编写的代码属于哪种风格?而后哪一种编码风格您更喜欢?
丑陋的 try catch 代码块
优雅的Controller前端
上面的示例,还只是在Controller层,若是是在Service层,可能会有更多的try catch代码块。这将会严重影响代码的可读性、“美观性”。spring
因此若是是个人话,我确定偏向于第二种,我能够把更多的精力放在业务代码的开发,同时代码也会变得更加简洁。数据库
既然业务代码不显式地对异常进行捕获、处理,而异常确定仍是处理的,否则系统岂不是动不动就崩溃了,因此必须得有其余地方捕获并处理这些异常。json
那么问题来了,如何优雅的处理各类异常?服务器
什么是统一异常处理网络
Spring在3.2版本增长了一个注解@ControllerAdvice,能够与@ExceptionHandler、@InitBinder、@ModelAttribute 等注解注解配套使用,对于这几个注解的做用,这里不作过多赘述,如有不了解的,能够参考Spring3.2新注解@ControllerAdvice,先大概有个了解。数据结构
不过跟异常处理相关的只有注解@ExceptionHandler,从字面上看,就是 异常处理器 的意思,其实际做用也是:若在某个Controller类定义一个异常处理方法,并在方法上添加该注解,那么当出现指定的异常时,会执行该处理异常的方法,其可使用springmvc提供的数据绑定,好比注入HttpServletRequest等,还能够接受一个当前抛出的Throwable对象。mybatis
可是,这样一来,就必须在每个Controller类都定义一套这样的异常处理方法,由于异常能够是各类各样。这样一来,就会形成大量的冗余代码,并且若须要新增一种异常的处理逻辑,就必须修改全部Controller类了,很不优雅。mvc
固然你可能会说,那就定义个相似BaseController的基类,这样总行了吧。
这种作法虽然没错,但仍不尽善尽美,由于这样的代码有必定的侵入性和耦合性。简简单单的Controller,我为啥非得继承这样一个类呢,万一已经继承其余基类了呢。你们都知道Java只能继承一个类。
那有没有一种方案,既不须要跟Controller耦合,也能够将定义的 异常处理器 应用到全部控制器呢?因此注解@ControllerAdvice出现了,简单的说,该注解能够把异常处理器应用到全部控制器,而不是单个控制器。借助该注解,咱们能够实现:在独立的某个地方,好比单独一个类,定义一套对各类异常的处理机制,而后在类的签名加上注解@ControllerAdvice,统一对 不一样阶段的、不一样异常 进行处理。这就是统一异常处理的原理。
注意到上面对异常按阶段进行分类,大致能够分红:进入Controller前的异常 和Service 层异常,具体能够参考下图:
不一样阶段的异常
目标
消灭95%以上的 try catch 代码块,以优雅的 Assert(断言) 方式来校验业务的异常状况,只关注业务逻辑,而不用花费大量精力写冗余的 try catch 代码块。
统一异常处理实战
在定义统一异常处理类以前,先来介绍一下如何优雅的断定异常状况并抛异常。
用 Assert(断言) 替换 throw exception
想必 Assert(断言) 你们都很熟悉,好比 Spring 家族的org.springframework.util.Assert,在咱们写测试用例的时候常常会用到,使用断言能让咱们编码的时候有一种非通常丝滑的感受,好比:
@Test public void test1() { ... User user = userDao.selectById(userId); Assert.notNull(user, "用户不存在."); ... } @Test public void test2() { // 另外一种写法 User user = userDao.selectById(userId); if (user == null) { throw new IllegalArgumentException("用户不存在."); } }
有没有感受第一种断定非空的写法很优雅,第二种写法则是相对丑陋的 if {…} 代码块。那么神奇的 Assert.notNull() 背后到底作了什么呢?下面是 Assert 的部分源码:
public abstract class Assert { public Assert() { } public static void notNull(@Nullable Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } }
能够看到,Assert 其实就是帮咱们把 if {…} 封装了一下,是否是很神奇。虽然很简单,但不能否认的是编码体验至少提高了一个档次。那么咱们能不能模仿org.springframework.util.Assert,也写一个断言类,不过断言失败后抛出的异常不是IllegalArgumentException 这些内置异常,而是咱们本身定义的异常。下面让咱们来尝试一下。
Assert
public interface Assert { /** * 建立异常 * @param args * @return */ BaseException newException(Object... args); /** * 建立异常 * @param t * @param args * @return */ BaseException newException(Throwable t, Object... args); /** * <p>断言对象<code>obj</code>非空。若是对象<code>obj</code>为空,则抛出异常 * * @param obj 待判断对象 */ default void assertNotNull(Object obj) { if (obj == null) { throw newException(obj); } } /** * <p>断言对象<code>obj</code>非空。若是对象<code>obj</code>为空,则抛出异常 * <p>异常信息<code>message</code>支持传递参数方式,避免在判断以前进行字符串拼接操做 * * @param obj 待判断对象 * @param args message占位符对应的参数列表 */ default void assertNotNull(Object obj, Object... args) { if (obj == null) { throw newException(args); } } }
上面的Assert断言方法是使用接口的默认方法定义的,而后有没有发现当断言失败后,抛出的异常不是具体的某个异常,而是交由2个newException接口方法提供。由于业务逻辑中出现的异常基本都是对应特定的场景,好比根据用户id获取用户信息,查询结果为null,此时抛出的异常可能为UserNotFoundException,而且有特定的异常码(好比7001)和异常信息“用户不存在”。因此具体抛出什么异常,有Assert的实现类决定。
看到这里,您可能会有这样的疑问,按照上面的说法,那岂不是有多少异常状况,就得有定义等量的断言类和异常类,这显然是反人类的,这也没想象中高明嘛。别急,且听我细细道来。
善解人意的Enum
自定义异常BaseException有2个属性,即code、message,这样一对属性,有没有想到什么类通常也会定义这2个属性?没错,就是枚举类。且看我如何将 Enum 和 Assert 结合起来,相信我必定会让你眼前一亮。以下:
public interface IResponseEnum { int getCode(); String getMessage(); } /** * <p>业务异常</p> * <p>业务处理时,出现异常,能够抛出该异常</p> */ 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); } } public interface BusinessExceptionAssert extends IResponseEnum, Assert { @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); } } @Getter @AllArgsConstructor public enum ResponseEnum implements BusinessExceptionAssert { /** * Bad licence type */ BAD_LICENCE_TYPE(7001, "Bad licence type."), /** * Licence not found */ LICENCE_NOT_FOUND(7002, "Licence not found.") ; /** * 返回码 */ private int code; /** * 返回消息 */ private String message; }
看到这里,有没有眼前一亮的感受,代码示例中定义了两个枚举实例:
BAD_LICENCE_TYPE、LICENCE_NOT_FOUND,分别对应了BadLicenceTypeException、LicenceNotFoundException两种异常。之后每增长一种异常状况,只需增长一个枚举实例便可,不再用每一种异常都定义一个异常类了。而后再来看下如何使用,假设LicenceService有校验Licence是否存在的方法,以下:
/** * 校验{@link Licence}存在 * @param licence */ private void checkNotNull(Licence licence) { ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence); } 若不使用断言,代码可能以下: private void checkNotNull(Licence licence) { if (licence == null) { throw new LicenceNotFoundException(); // 或者这样 throw new BusinessException(7001, "Bad licence type."); } }
使用枚举类结合(继承)Assert,只需根据特定的异常状况定义不一样的枚举实例,如上面的BAD_LICENCE_TYPE、LICENCE_NOT_FOUND,就可以针对不一样状况抛出特定的异常(这里指携带特定的异常码和异常消息),这样既不用定义大量的异常类,同时还具有了断言的良好可读性,固然这种方案的好处远不止这些,请继续阅读后文,慢慢体会。
注:上面举的例子是针对特定的业务,而有部分异常状况是通用的,好比:服务器繁忙、网络异常、服务器异常、参数校验异常、404等,因此有CommonResponseEnum、ArgumentResponseEnum、ServletResponseEnum,其中ServletResponseEnum 会在后文详细说明。
定义统一异常处理器类
@Slf4j @Component @ControllerAdvice @ConditionalOnWebApplication @ConditionalOnMissingBean(UnifiedExceptionHandler.class) public class UnifiedExceptionHandler { /** * 生产环境 */ private final static String ENV_PROD = "prod"; @Autowired private UnifiedMessageSource unifiedMessageSource; /** * 当前环境 */ @Value("${spring.profiles.active}") private String profile; /** * 获取国际化消息 * * @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; } /** * 业务异常 * * @param e 异常 * @return 异常结果 */ @ExceptionHandler(value = BusinessException.class) @ResponseBody public ErrorResponse handleBusinessException(BaseException e) { log.error(e.getMessage(), e); return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e)); } /** * 自定义异常 * * @param e 异常 * @return 异常结果 */ @ExceptionHandler(value = BaseException.class) @ResponseBody public ErrorResponse handleBaseException(BaseException e) { log.error(e.getMessage(), e); return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e)); } /** * Controller上一层相关异常 * * @param e 异常 * @return 异常结果 */ @ExceptionHandler({ NoHandlerFoundException.class, HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class, MissingPathVariableException.class, MissingServletRequestParameterException.class, TypeMismatchException.class, HttpMessageNotReadableException.class, HttpMessageNotWritableException.class, // BindException.class, // MethodArgumentNotValidException.class HttpMediaTypeNotAcceptableException.class, ServletRequestBindingException.class, ConversionNotSupportedException.class, MissingServletRequestPartException.class, AsyncRequestTimeoutException.class }) @ResponseBody public ErrorResponse handleServletException(Exception e) { log.error(e.getMessage(), e); int code = CommonResponseEnum.SERVER_ERROR.getCode(); try { ServletResponseEnum servletExceptionEnum = ServletResponseEnum.valueOf(e.getClass().getSimpleName()); code = servletExceptionEnum.getCode(); } catch (IllegalArgumentException e1) { log.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 new ErrorResponse(code, message); } return new ErrorResponse(code, e.getMessage()); } /** * 参数绑定异常 * * @param e 异常 * @return 异常结果 */ @ExceptionHandler(value = BindException.class) @ResponseBody public ErrorResponse handleBindException(BindException e) { log.error("参数绑定校验异常", e); return wrapperBindingResult(e.getBindingResult()); } /** * 参数校验异常,将校验失败的全部异常组合成一条错误信息 * * @param e 异常 * @return 异常结果 */ @ExceptionHandler(value = MethodArgumentNotValidException.class) @ResponseBody public ErrorResponse handleValidException(MethodArgumentNotValidException e) { log.error("参数绑定校验异常", e); return wrapperBindingResult(e.getBindingResult()); } /** * 包装绑定异常结果 * * @param bindingResult 绑定结果 * @return 异常结果 */ private ErrorResponse 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 new ErrorResponse(ArgumentResponseEnum.VALID_ERROR.getCode(), msg.substring(2)); } /** * 未定义异常 * * @param e 异常 * @return 异常结果 */ @ExceptionHandler(value = Exception.class) @ResponseBody public ErrorResponse handleException(Exception e) { log.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 new ErrorResponse(code, message); } return new ErrorResponse(CommonResponseEnum.SERVER_ERROR.getCode(), e.getMessage()); } }
能够看到,上面将异常分红几类,实际上只有两大类,一类是ServletException、ServiceException,还记得上文提到的 按阶段分类 吗,即对应 进入Controller前的异常 和 Service 层异常;而后 ServiceException 再分红自定义异常、未知异常。对应关系以下:
接下来分别对这几种异常处理器作详细说明。
异常处理器说明
handleServletException
一个http请求,在到达Controller前,会对该请求的请求信息与目标控制器信息作一系列校验。这里简单说一下:
handleBindException
参数校验异常,后文详细说明。
handleValidException
参数校验异常,后文详细说明。
handleBusinessException、handleBaseException
处理自定义的业务异常,只是handleBaseException处理的是除了 BusinessException 意外的全部业务异常。就目前来看,这2个是能够合并成一个的。
handleException
处理全部未知的异常,好比操做数据库失败的异常。
注:上面的handleServletException、handleException 这两个处理器,返回的异常信息,不一样环境返回的可能不同,觉得这些异常信息都是框架自带的异常信息,通常都是英文的,不太好直接展现给用户看,因此统一返回SERVER_ERROR表明的异常信息。
异于常人的404
上文提到,当请求没有匹配到控制器的状况下,会抛出NoHandlerFoundException异常,但其实默认状况下不是这样,默认状况下会出现相似以下页面:
Whitelabel Error Page
这个页面是如何出现的呢?实际上,当出现404的时候,默认是不抛异常的,而是forward跳转到/error控制器,spring也提供了默认的error控制器,以下:
BasicErrorController
那么,如何让404也抛出异常呢,只需在properties文件中加入以下配置便可:
spring.mvc.throw-exception-if-no-handler-found=true
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包。项目结构以下:
项目结构
之后只需这样引入便可
引入common包
主要代码
下面是用于验证的主要源码:
@Service public class LicenceService extends ServiceImpl<LicenceMapper, Licence> { @Autowired private OrganizationClient organizationClient; /** * 查询{@link Licence} 详情 * @param licenceId * @return */ public LicenceDTO queryDetail(Long licenceId) { Licence licence = this.getById(licenceId); checkNotNull(licence); OrganizationDTO org = ClientUtil.execute(() -> organizationClient.getOrganization(licence.getOrganizationId())); return toLicenceDTO(licence, org); } /** * 分页获取 * @param licenceParam 分页查询参数 * @return */ public QueryData<SimpleLicenceDTO> getLicences(LicenceParam licenceParam) { String licenceType = licenceParam.getLicenceType(); LicenceTypeEnum licenceTypeEnum = LicenceTypeEnum.parseOfNullable(licenceType); // 断言, 非空 ResponseEnum.BAD_LICENCE_TYPE.assertNotNull(licenceTypeEnum); LambdaQueryWrapper<Licence> wrapper = new LambdaQueryWrapper<>(); wrapper.eq(Licence::getLicenceType, licenceType); IPage<Licence> page = this.page(new QueryPage<>(licenceParam), wrapper); return new QueryData<>(page, this::toSimpleLicenceDTO); } /** * 新增{@link Licence} * @param request 请求体 * @return */ @Transactional(rollbackFor = Throwable.class) public LicenceAddRespData addLicence(LicenceAddRequest request) { Licence licence = new Licence(); licence.setOrganizationId(request.getOrganizationId()); licence.setLicenceType(request.getLicenceType()); licence.setProductName(request.getProductName()); licence.setLicenceMax(request.getLicenceMax()); licence.setLicenceAllocated(request.getLicenceAllocated()); licence.setComment(request.getComment()); this.save(licence); return new LicenceAddRespData(licence.getLicenceId()); } /** * entity -> simple dto * @param licence {@link Licence} entity * @return {@link SimpleLicenceDTO} */ private SimpleLicenceDTO toSimpleLicenceDTO(Licence licence) { // 省略 } /** * entity -> dto * @param licence {@link Licence} entity * @param org {@link OrganizationDTO} * @return {@link LicenceDTO} */ private LicenceDTO toLicenceDTO(Licence licence, OrganizationDTO org) { // 省略 } /** * 校验{@link Licence}存在 * @param licence */ private void checkNotNull(Licence licence) { ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence); } }
ps: 这里使用的DAO框架是mybatis-plus。
启动时,自动插入的数据为:
-- licence INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated) VALUES (1, 1, 'user','CustomerPro', 100,5); INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated) VALUES (2, 1, 'user','suitability-plus', 200,189); INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated) VALUES (3, 2, 'user','HR-PowerSuite', 100,4); INSERT INTO licence (licence_id, organization_id, licence_type, product_name, licence_max, licence_allocated) VALUES (4, 2, 'core-prod','WildCat Application Gateway', 16,16); -- organizations INSERT INTO organization (id, name, contact_name, contact_email, contact_phone) VALUES (1, 'customer-crm-co', 'Mark Balster', 'mark.balster@custcrmco.com', '823-555-1212'); INSERT INTO organization (id, name, contact_name, contact_email, contact_phone) VALUES (2, 'HR-PowerSuite', 'Doug Drewry','doug.drewry@hr.com', '920-555-1212');
开始验证
捕获自定义异常
获取不存在的 licence 详情:http://localhost:10000/licence/5。成功响应的请求:licenceId=1
校验非空
捕获 Licence not found 异常
Licence not found
2.根据不存在的 licence type 获取 licence 列表:http://localhost:10000/licenc...。可选的 licence type 为:user、core-prod 。
校验非空
捕获 Bad licence type 异常
Bad licence type
捕获进入 Controller 前的异常
访问不存在的接口:http://localhost:10000/licenc...
捕获404异常
http 方法不支持:http://localhost:10000/licence
PostMapping
捕获 Request method not supported 异常
Request method not supported
3 校验异常1:http://localhost:10000/licenc...
getLicences
LicenceParam
捕获参数绑定校验异常
licence type cannot be empty
4.校验异常2:post 请求,这里使用postman模拟。
addLicence
LicenceAddRequest
请求url即结果
捕获参数绑定校验异常
注:由于参数绑定校验异常的异常信息的获取方式与其它异常不同,因此才把这2种状况的异常从 进入 Controller 前的异常 单独拆出来,下面是异常信息的收集逻辑:
异常信息的收集
捕获未知异常
假设咱们如今随便对 Licence 新增一个字段 test,但不修改数据库表结构,而后访问:http://localhost:10000/licence/1。
增长test字段
捕获数据库异常
Error querying database
小结
能够看到,测试的异常都可以被捕获,而后以 code、message 的形式返回。每个项目/模块,在定义业务异常的时候,只需定义一个枚举类,而后实现接口BusinessExceptionAssert,最后为每一种业务异常定义对应的枚举实例便可,而不用定义许多异常类。使用的时候也很方便,用法相似断言。
扩展
在生产环境,若捕获到 未知异常 或者 ServletException,由于都是一长串的异常信息,若直接展现给用户看,显得不够专业,因而,咱们能够这样作:当检测到当前环境是生产环境,那么直接返回 “网络异常”。
生产环境返回“网络异常”
能够经过如下方式修改当前环境:
修改当前环境为生产环境
总结
使用 断言 和 枚举类 相结合的方式,再配合统一异常处理,基本大部分的异常都可以被捕获。为何说大部分异常,由于当引入 spring cloud security 后,还会有认证/受权异常,网关的服务降级异常、跨模块调用异常、远程调用第三方服务异常等,这些异常的捕获方式与本文介绍的不太同样,不过限于篇幅,这里不作详细说明,之后会有单独的文章介绍。
另外,当须要考虑国际化的时候,捕获异常后的异常信息通常不能直接返回,须要转换成对应的语言,不过本文已考虑到了这个,获取消息的时候已经作了国际化映射,逻辑以下:
获取国际化消息
最后总结,全局异常属于老生长谈的话题,但愿此次经过手机的项目对你们有点指导性的学习。你们根据实际状况自行修改。
也能够采用如下的jsonResult对象的方式进行处理,也贴出来代码.
@Slf4j @RestControllerAdvice public class GlobalExceptionHandler { /** * 没有登陆 * @param request * @param response * @param e * @return */ @ExceptionHandler(NoLoginException.class) public Object noLoginExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e) { log.error("[GlobalExceptionHandler][noLoginExceptionHandler] exception",e); JsonResult jsonResult = new JsonResult(); jsonResult.setCode(JsonResultCode.NO_LOGIN); jsonResult.setMessage("用户登陆失效或者登陆超时,请先登陆"); return jsonResult; } /** * 业务异常 * @param request * @param response * @param e * @return */ @ExceptionHandler(ServiceException.class) public Object businessExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e) { log.error("[GlobalExceptionHandler][businessExceptionHandler] exception",e); JsonResult jsonResult = new JsonResult(); jsonResult.setCode(JsonResultCode.FAILURE); jsonResult.setMessage("业务异常,请联系管理员"); return jsonResult; } /** * 全局异常处理 * @param request * @param response * @param e * @return */ @ExceptionHandler(Exception.class) public Object exceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e) { log.error("[GlobalExceptionHandler][exceptionHandler] exception",e); JsonResult jsonResult = new JsonResult(); jsonResult.setCode(JsonResultCode.FAILURE); jsonResult.setMessage("系统错误,请联系管理员"); return jsonResult; } }