熟练使用SpringBoot--使用ControllerAdvice或RestControllerAdvice处理异常

熟练使用-SpringBoot

前言

在Spring 3.2中,新增了@ControllerAdvice、@RestControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping、@PostMapping, @GetMapping注解中。

注解使用

定义一个全局的异常拦截器
熟练使用SpringBoot--使用ControllerAdvice或RestControllerAdvice处理异常
注意:

@ExceptionHandler注解传入的参数可以一个数组,使用该注解时,传入的参数不能相同,就是不能两个@ExceptionHandler去处理一个异常,传入的参数相同,初始化ExceptionHandler失败

对于@ControllerAdvice注解,看一下源码熟练使用SpringBoot--使用ControllerAdvice或RestControllerAdvice处理异常
我们可以传递一个basePackages,声明的类(可以是数组)

异常处理

编写自定义异常处理类
熟练使用SpringBoot--使用ControllerAdvice或RestControllerAdvice处理异常

Spring对于RuntimeException类的异常才会进行事务回滚,所以一般自定义异常都继承该异常类

使用

熟练使用SpringBoot--使用ControllerAdvice或RestControllerAdvice处理异常
熟练使用SpringBoot--使用ControllerAdvice或RestControllerAdvice处理异常

说明

我们也可以使用@RestControllerAdvice替代@ControllerAdvice,这样方法上就可以不用添加@RequestBody,@RestControllerAdvice在注解上已经添加了@RequestBody