Java生鲜电商平台-统一异常处理及架构实战
Java生鲜电商平台-统一异常处理及架构实战 补充说明:本文讲得比较细,所以篇幅较长。 请认真读完,希望读完后能对统一异常处理有一个清晰的认识。 背景软件开发过程中,不可避免的是需要处理各种异常,就我自己来说,至少有一半以上的时间都是在处理各种异常情况,所以代码中就会出现大量的
?
丑陋的 try catch 代码块
?
优雅的Controller
上面的示例,还只是在 所以如果是我的话,我肯定偏向于第二种,我可以把更多的精力放在业务代码的开发,同时代码也会变得更加简洁。 既然业务代码不显式地对异常进行捕获、处理,而异常肯定还是处理的,不然系统岂不是动不动就崩溃了,所以必须得有其他地方捕获并处理这些异常。 那么问题来了,如何优雅的处理各种异常? 什么是统一异常处理
不过跟异常处理相关的只有注解 但是,这样一来,就必须在每一个 当然你可能会说,那就定义个类似 这种做法虽然没错,但仍不尽善尽美,因为这样的代码有一定的侵入性和耦合性。简简单单的 那有没有一种方案,既不需要跟
目标消灭95%以上的 统一异常处理实战在定义统一异常处理类之前,先来介绍一下如何优雅的判定异常情况并抛异常。 用 Assert(断言) 替换 throw exception想必 @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("用户不存在."); } }
有没有感觉第一种判定非空的写法很优雅,第二种写法则是相对丑陋的 public abstract class Assert { public Assert() { } public static void notNull(@Nullable Object object,String message) { if (object == null) { throw new IllegalArgumentException(message); } } }
可以看到, Assertpublic 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); } } }
上面的 看到这里,您可能会有这样的疑问,按照上面的说法,那岂不是有多少异常情况,就得有定义等量的断言类和异常类,这显然是反人类的,这也没想象中高明嘛。别急,且听我细细道来。 善解人意的Enum自定义异常 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,String message,Throwable cause) { super(responseEnum,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,msg); } @Override default BaseException newException(Throwable t,Object... args) { String msg = MessageFormat.format(this.getMessage(),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; }
看到这里,有没有眼前一亮的感觉,代码示例中定义了两个枚举实例: /** * 校验{@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."); } }
使用枚举类结合(继承)
定义统一异常处理器类@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(),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()); } }
可以看到,上面将异常分成几类,实际上只有两大类,一类是
接下来分别对这几种异常处理器做详细说明。 异常处理器说明handleServletException一个
handleBindException参数校验异常,后文详细说明。 handleValidException参数校验异常,后文详细说明。 handleBusinessException、handleBaseException处理自定义的业务异常,只是 handleException处理所有未知的异常,比如操作数据库失败的异常。
异于常人的404上文提到,当请求没有匹配到控制器的情况下,会抛出
?
Whitelabel Error Page
? 这个页面是如何出现的呢?实际上,当出现404的时候,默认是不抛异常的,而是
?
BasicErrorController
? 那么,如何让404也抛出异常呢,只需在 spring.mvc.throw-exception-if-no-handler-found=true spring.resources.add-mappings=false
如此,就可以异常处理器中捕获它了,然后前端只要捕获到特定的状态码,立即跳转到404页面即可
?
捕获404对应的异常
? 统一返回结果在验证统一异常处理器之前,顺便说一下统一返回结果。说白了,其实是统一一下返回结果的数据结构。 所以首先定义一个 然后定义一个通用返回结果类 为了区分成功和失败返回结果,于是再定义一个 最后还有一种常见的返回结果,即返回的数据带有分页信息,因为这种接口比较常见,所以有必要单独定义一个返回结果类 其中比较常用的只有 所有的返回结果类的定义这里就不贴出来了 验证统一异常处理因为这一套统一异常处理可以说是通用的,所有可以设计成一个
?
项目结构
以后只需这样引入即可
?
引入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); } }
-- 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,licence_allocated) VALUES (2,‘suitability-plus‘,200,189); INSERT INTO licence (licence_id,licence_allocated) VALUES (3,2,‘HR-PowerSuite‘,4); INSERT INTO licence (licence_id,licence_allocated) VALUES (4,‘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‘,‘[email?protected]‘,‘823-555-1212‘); INSERT INTO organization (id,contact_phone) VALUES (2,‘Doug Drewry‘,‘[email?protected]‘,‘920-555-1212‘);
开始验证捕获自定义异常
捕获进入 Controller 前的异常
捕获未知异常假设我们现在随便对
?
增加test字段
?
捕获数据库异常
?
Error querying database
? 小结可以看到,测试的异常都能够被捕获,然后以 扩展在生产环境,若捕获到 未知异常 或者
?
生产环境返回“网络异常”
可以通过以下方式修改当前环境:
?
修改当前环境为生产环境
? 总结使用 断言 和 枚举类 相结合的方式,再配合统一异常处理,基本大部分的异常都能够被捕获。为什么说大部分异常,因为当引入 另外,当需要考虑国际化的时候,捕获异常后的异常信息一般不能直接返回,需要转换成对应的语言,不过本文已考虑到了这个,获取消息的时候已经做了国际化映射,逻辑如下:
?
获取国际化消息
?
?
最后总结,全局异常属于老生长谈的话题,希望这次通过手机的项目对大家有点指导性的学习。大家根据实际情况自行修改。
?
也可以采用以下的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,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,Exception e) { log.error("[GlobalExceptionHandler][exceptionHandler] exception",e); JsonResult jsonResult = new JsonResult(); jsonResult.setCode(JsonResultCode.FAILURE); jsonResult.setMessage("系统错误,请联系管理员"); return jsonResult; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |