spring boot 环境下的统一异常处理大家已经非常熟悉了,不熟悉的化可以参考<<Spring Boot中Web应用的统一异常处理>>。公司内部的统一异常处理如下:
@ExceptionHandler public ResultEntity<?> handler(HttpServletRequest req, HttpServletResponse res, Exception e) { logger.info("统一异常处理,Restful Http请求发生异常,HTTP响应码信息:{}", res.getStatus()); ResultEntity<?> resultEntity = new ResultEntity(); if (e instanceof BizException) { logger.error("统一异常处理,异常代码00:" + e.getMessage()); resultEntity.setCode(this.getReturnCode(((BizException)e).getCode())); resultEntity.setMsg(((BizException)e).getMsg()); return resultEntity; } else if (e instanceof NullPointerException) { exceptionCount.incrementAndGet(); logger.error("统一异常处理,异常代码01:" + e.getMessage(), e); resultEntity.setCode(this.getReturnCode(ReturnCodeEnum.NULL_POINTER_EXCEPTION.code)); resultEntity.setMsg(ReturnCodeEnum.NULL_POINTER_EXCEPTION.msg); return resultEntity; }可以看到它设定的返回出参的json格式为:
{ "code": "7060124001", "msg": "参数校验未通过:[不能为空]" }项目需要重构。这个模块业务返回的接口json格式应该为:
{ "respCode": "7060124001", "respDesc": "参数校验未通过:[不能为空]", "respInfo": null }我们是否可以定义一个@RestControllerAdvice,并在spring boot 生效?实验后是可以。在定义两个@RestControllerAdvice后日志输出有两个:
Detected @ExceptionHandler methods in myControllerAdvice| Detected @ExceptionHandler methods in controllerExceptionHandleAdvice|自定义的myControllerAdvice也是生效的。如果你需要排除基础jar包controllerExceptionHandleAdvice带来的影响,你可以在启动类上加上如下注解:
@ComponentScan(value="com.epay.ts.piss.basic.springboot",excludeFilters= {@ComponentScan.Filter(type= FilterType.ASSIGNABLE_TYPE, value= {ControllerExceptionHandleAdvice.class})})上面注解的学习可以参见spring boot去除扫描自动注入依赖方法