Springboot全局异常处理GlobalExceptionHandler

1. Springboot的全局异常查是通过两个注解@ControllerAdvice@ExceptionHandler来实现的

@ControllerAdvice:增强型控制器,对于控制器的全局配置放在同一个位置,全局异常的注解,放在类上。

                                 @ControllerAdvice默认只会处理controller层抛出的异常,如果需要处理service层的异常,需要定义一个自                                    定义的MyException来继承RuntimeException类,然后@ExceptionHandler(MyException)即可。

@ExceptionHandler:指明需要处理的异常类型以及子类。注解放在方法上面。

2. 基本使用

2.1 @ControllerAdvice 注解定义全局异常处理类

      确保此 GlobalExceptionHandler 类能被扫描到并装载进 Spring 容器中

@ControllerAdvice
public class GlobalExceptionHandler {
}

2.2 @ExceptionHandler 注解声明异常处理方法

      方法 handleException() 就会处理所有 Controller 层抛出的 Exception 及其子类的异常

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    String handleException(){
        return "Exception Deal!";
    }
}

3. 代码示例

@ControllerAdvice
public class GlobalExceptionHandler {
 
    @ExceptionHandler()
    public ResponseEntity exceptionHandle(Exception e){ // 处理方法参数的异常类型
        return null;//自己需要实现的异常处理
    }
 
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ResponseEntity handle(BaseException e){
        return null; //自己需要实现的异常处理
    }
 

a. @ExceptionHandler(RuntimeException.class): 会先查看异常是否属于RuntimeException异常以及其子类,如果是的话,就用这个方法进行处理。

b. 一个方法处理多个异常类的异常:@ExceptionHandler(value={RuntimeException.class,MyRuntimeException.class})

c. @ExceptionHandler(如果不指定异常类型):默认会根据方法参数的异常类型进行处理。

    如:  public ResponseEntity handle(BaseException e)  

d. 有多个@ExceptionHandler注解的方法时,会根据抛出异常类去寻找处理方法,如果没有,就往上找父类,直到找到为止。

4. 优缺点

优点:将 Controller 层的异常和数据校验的异常进行统一处理,减少模板代码,减少编码量,提升扩展性和可维护性。

缺点:只能处理 Controller 层未捕获(往外抛)的异常,对于 Interceptor(拦截器)层的异常,Spring 框架层的异常,就无                   能为力了。

参考连接:  https://blog.csdn.net/weixin_40326509/article/details/81268612

                 https://blog.csdn.net/kinginblue/article/details/70186586

你可能感兴趣的:(springboot,springboot)