@ControllerAdvice + @ExceptionHandler 全局处理 Controller 层异常
点击关注 ? Java基基 文章源自JAVA秀-https://www.javaxiu.com/66713.html
点击上方“Java基基”,选择“设为星标”文章源自JAVA秀-https://www.javaxiu.com/66713.html
做积极的人,而不是积极废人!文章源自JAVA秀-https://www.javaxiu.com/66713.html
每天 14:00 更新文章,每天掉亿点点头发...文章源自JAVA秀-https://www.javaxiu.com/66713.html
文章源自JAVA秀-https://www.javaxiu.com/66713.html
源码精品专栏文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
原创 | Java 2021 超神之路,很肝~文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
中文详细注释的开源项目文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
RPC 框架 Dubbo 源码解析文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
网络应用框架 Netty 源码解析文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
消息中间件 RocketMQ 源码解析文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
数据库中间件 Sharding-JDBC 和 MyCAT 源码解析文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
作业调度中间件 Elastic-Job 源码解析文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
分布式事务中间件 TCC-Transaction 源码解析文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
Eureka 和 Hystrix 源码解析文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
Java 并发源码文章源自JAVA秀-https://www.javaxiu.com/66713.html
来源:cnblogs.com/AlanWilliamWalker文章源自JAVA秀-https://www.javaxiu.com/66713.html
/p/9993845.html文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
1.利用springmvc注解对Controller层异常全局处理文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
1.1优缺点文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
1.2基本使用文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
1.3处理Service层上抛的业务异常文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
1.4处理Controller数据绑定、数据校验的异常文章源自JAVA秀-https://www.javaxiu.com/66713.html
文章源自JAVA秀-https://www.javaxiu.com/66713.html
1.利用springmvc注解对Controller层异常全局处理
对于与数据库相关的 Spring MVC 项目,我们通常会把 事务 配置在 Service层,当数据库操作失败时让 Service 层抛出运行时异常,Spring 事物管理器就会进行回滚。文章源自JAVA秀-https://www.javaxiu.com/66713.html
如此一来,我们的 Controller 层就不得不进行 try-catch
Service 层的异常,否则会返回一些不友好的错误信息到客户端。但是,Controller 层每个方法体都写一些模板化的 try-catch
的代码,很难看也难维护,特别是还需要对 Service 层的不同异常进行不同处理的时候。文章源自JAVA秀-https://www.javaxiu.com/66713.html
1.1优缺点
优点: 将Controller层的异常和数据校验的异常进行统一异常处理,减少模板代码,减少代码量,提升扩展性和可维护性文章源自JAVA秀-https://www.javaxiu.com/66713.html
缺点: 只能处理Controller层未捕获(从Servcie层抛过来)的异常,对于Interceptor(拦截器)层的异常,Spring框架层的异常,就无能为力了。文章源自JAVA秀-https://www.javaxiu.com/66713.html
1.2基本使用
首先,确保此类GlobalExceptionHandler
能被扫描到并装载进Spring容器中。文章源自JAVA秀-https://www.javaxiu.com/66713.html
@ControllerAdvicepublic class GlobalExceptionHandler {}
@ControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody String handleException(){ return "Exception Deal!"; }}
方法 handleException()
就会处理所有 Controller
层抛出的 Exception
及其子类的异常,这是最基本的用法了。文章源自JAVA秀-https://www.javaxiu.com/66713.html
被 @ExceptionHandler
注解的方法的参数列表里,还可以声明很多种类型的参数。其原型如下:文章源自JAVA秀-https://www.javaxiu.com/66713.html
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface ExceptionHandler { /** * Exceptions handled by the annotated method. If empty, will default to any * exceptions listed in the method argument list. */ Class<? extends Throwable>[] value() default {};}
如果 @ExceptionHandler
注解中未声明要处理的异常类型,则默认为参数列表中的异常类型。所以上面的写法,还可以写成这样:文章源自JAVA秀-https://www.javaxiu.com/66713.html
@ControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler() @ResponseBody String handleException(Exception e){ return "Exception Deal! " + e.getMessage(); }}
参数对象就是 Controller
层抛出的异常对象!文章源自JAVA秀-https://www.javaxiu.com/66713.html
1.3处理Service层上抛的业务异常
@ControllerAdvicepublic class GlobalExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 处理所有不可知的异常 * @param e * @return */ @ExceptionHandler(Exception.class) @ResponseBody AppResponse handleException(Exception e){ LOGGER.error(e.getMessage(), e); AppResponse response = new AppResponse(); response.setFail("操作失败!"); return response; } /** * 处理所有业务异常 * @param e * @return */ @ExceptionHandler(BusinessException.class) @ResponseBody AppResponse handleBusinessException(BusinessException e){ LOGGER.error(e.getMessage(), e); AppResponse response = new AppResponse(); response.setFail(e.getMessage()); return response; }}
BusinessException
属于业务自定义异常类文章源自JAVA秀-https://www.javaxiu.com/66713.html
@RestController@RequestMapping(value = "/dogs", consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE})public class DogController { @Autowired private DogService dogService; @PatchMapping(value = "") Dog update(@Validated(Update.class) @RequestBody Dog dog){ return dogService.update(dog); }}
这样Controller层就不需要进行异常处理了;文章源自JAVA秀-https://www.javaxiu.com/66713.html
有时我们会在复杂带有数据库事务的业务中,当出现不和预期的数据时,直接抛出封装后的业务级运行时异常,进行数据库事务回滚,并希望该异常信息能被返回显示给用户。文章源自JAVA秀-https://www.javaxiu.com/66713.html
我们可以使用自定义异常类可以针对具体业务处理异常;文章源自JAVA秀-https://www.javaxiu.com/66713.html
Logger 进行所有的异常日志记录。文章源自JAVA秀-https://www.javaxiu.com/66713.html
-
@ExceptionHandler(BusinessException.class)
声明了对 BusinessException 业务异常的处理,并获取该业务异常中的错误提示,构造后返回给客户端。文章源自JAVA秀-https://www.javaxiu.com/66713.html -
@ExceptionHandler(Exception.class)
声明了对 Exception 异常的处理,起到兜底作用,不管 Controller 层执行的代码出现了什么未能考虑到的异常,都返回统一的错误提示给客户端。文章源自JAVA秀-https://www.javaxiu.com/66713.html
备注:以上
GlobalExceptionHandler
只是返回 Json 给客户端,更大的发挥空间需要按需求情况来做。但是实际开发中并不这么做,因为返回的Response对象可能封装不同的数据,放在同一异常处理固然是方便,但是可能不实用;文章源自JAVA秀-https://www.javaxiu.com/66713.html
1.4处理Controller数据绑定、数据校验的异常
在Dog类中的字段上的注解数据校验规则:文章源自JAVA秀-https://www.javaxiu.com/66713.html
@Datapublic class Dog { @NotNull(message = "{Dog.id.non}", groups = {Update.class}) @Min(value = 1, message = "{Dog.age.lt1}", groups = {Update.class}) private Long id; @NotBlank(message = "{Dog.name.non}", groups = {Add.class, Update.class}) private String name; @Min(value = 1, message = "{Dog.age.lt1}", groups = {Add.class, Update.class}) private Integer age;}
说明:文章源自JAVA秀-https://www.javaxiu.com/66713.html
@NotNull、@Min、@NotBlank
这些注解的使用方法,不在本文范围内。如果不熟悉,请查找资料学习即可。文章源自JAVA秀-https://www.javaxiu.com/66713.html
其他说明:文章源自JAVA秀-https://www.javaxiu.com/66713.html
@Data 注解是 Lombok 项目的注解,可以使我们不用再在代码里手动加 getter & setter。文章源自JAVA秀-https://www.javaxiu.com/66713.html
在 Eclipse 和 IntelliJ IDEA 中使用时,还需要安装相关插件,这个步骤自行Google/Baidu 吧!文章源自JAVA秀-https://www.javaxiu.com/66713.html
基本使用:文章源自JAVA秀-https://www.javaxiu.com/66713.html
SpringMVC 中对于 RESTFUL 的 Json 接口来说,数据绑定和校验,是这样的:文章源自JAVA秀-https://www.javaxiu.com/66713.html
/** * 使用 GlobalExceptionHandler 全局处理 Controller 层异常的示例 * @param dog * @return */@PatchMapping(value = "")AppResponse update(@Validated(Update.class) @RequestBody Dog dog){ AppResponse resp = new AppResponse(); // 执行业务 Dog newDog = dogService.update(dog); // 返回数据 resp.setData(newDog); return resp;}
使用 @Validated + @RequestBody
注解实现。文章源自JAVA秀-https://www.javaxiu.com/66713.html
当使用了 @Validated + @RequestBody
注解但是没有在绑定的数据对象后面跟上 Errors 类型的参数声明的话,Spring MVC 框架会抛出 MethodArgumentNotValidException
异常。文章源自JAVA秀-https://www.javaxiu.com/66713.html
所以,在 GlobalExceptionHandler
中加上对 MethodArgumentNotValidException
异常的声明和处理,就可以全局处理数据校验的异常了!加完后的代码如下:文章源自JAVA秀-https://www.javaxiu.com/66713.html
/** * @ControllerAdvice + @ExceptionHandler 实现全局的 Controller 层的异常处理 */@ControllerAdvicepublic class GlobalExceptionHandler { private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 处理所有不可知的异常 * @param e * @return */ @ExceptionHandler(Exception.class) @ResponseBody AppResponse handleException(Exception e){ LOGGER.error(e.getMessage(), e); AppResponse response = new AppResponse(); response.setFail("操作失败!"); return response; } /** * 处理所有业务异常 * @param e * @return */ @ExceptionHandler(BusinessException.class) @ResponseBody AppResponse handleBusinessException(BusinessException e){ LOGGER.error(e.getMessage(), e); AppResponse response = new AppResponse(); response.setFail(e.getMessage()); return response; } /** * 处理所有接口数据验证异常 * @param e * @return */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody AppResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e){ LOGGER.error(e.getMessage(), e); AppResponse response = new AppResponse(); response.setFail(e.getBindingResult().getAllErrors().get(0).getDefaultMessage()); return response; }}
注意到了吗,所有的 Controller
层的异常的日志记录,都是在这个 GlobalExceptionHandler
中进行记录。也就是说,Controller
层也不需要在手动记录错误日志了。文章源自JAVA秀-https://www.javaxiu.com/66713.html
其实,可以利用springaop进行拦截,然后记录日志。文章源自JAVA秀-https://www.javaxiu.com/66713.html
其实,被 @ExceptionHandler
注解的方法还可以声明很多参数,详见文档。文章源自JAVA秀-https://www.javaxiu.com/66713.html
@ControllerAdvice
也还可以结合 @InitBinder
、@ModelAttribute
等注解一起使用,应用在所有被 @RequestMapping
注解的方法上,详见搜索引擎。文章源自JAVA秀-https://www.javaxiu.com/66713.html
欢迎加入我的知识星球,一起探讨架构,交流源码。加入方式,长按下方二维码噢:文章源自JAVA秀-https://www.javaxiu.com/66713.html
文章源自JAVA秀-https://www.javaxiu.com/66713.html
已在知识星球更新源码解析如下:文章源自JAVA秀-https://www.javaxiu.com/66713.html
文章源自JAVA秀-https://www.javaxiu.com/66713.html
文章源自JAVA秀-https://www.javaxiu.com/66713.html
文章源自JAVA秀-https://www.javaxiu.com/66713.html
文章源自JAVA秀-https://www.javaxiu.com/66713.html
最近更新《芋道 SpringBoot 2.X 入门》系列,已经 101 余篇,覆盖了 MyBatis、Redis、MongoDB、ES、分库分表、读写分离、SpringMVC、Webflux、权限、WebSocket、Dubbo、RabbitMQ、RocketMQ、Kafka、性能测试等等内容。文章源自JAVA秀-https://www.javaxiu.com/66713.html
提供近 3W 行代码的 SpringBoot 示例,以及超 6W 行代码的电商微服务项目。文章源自JAVA秀-https://www.javaxiu.com/66713.html
获取方式:点“在看”,关注公众号并回复 666 领取,更多内容陆续奉上。文章源自JAVA秀-https://www.javaxiu.com/66713.html
文章源自JAVA秀-https://www.javaxiu.com/66713.html
文章有帮助的话,在看,转发吧。谢谢支持哟 (*^__^*)文章源自JAVA秀-https://www.javaxiu.com/66713.html

评论