美文网首页
springboot全局异常处理

springboot全局异常处理

作者: hk_faith | 来源:发表于2020-12-24 09:23 被阅读0次

1.java异常

java中的异常可是是函数中的语句引发的,也可以是通过 throw 显示的抛出去的。
只要java中有异常,就会有一个对应的异常对象来封装这个类。JRE就会试图寻找这个异常的对应的处理程序来处理。
java标准库内建了一些通用的异常,Throwable类是java异常类型的顶层父类,
Throwable有派生了Error类和Exception类

错误: Error类以及其他子类的实例,代表了JVM本身的错误,错误不能被
程序员通过代码来处理,Error 很少出现。

异常: Excrption以及他的子类,代表程序运行的时候发生了各种不期望
发生的事件,可以被Java异常处理机制使用 ,是异常处理的核心。

java异常处理机制.jpg

非检查异常: Error 和RuntimeException 以及他们的子类,java 编译的时候不会提示和发现这种异常,不要求
程序处理,所有如果意愿,我们可以编写(try..catch..finally)这样处理。也可以不处理。对这些异常,我们应该修正代码,而不是通过异常来处理,多半是以为代码有问题

检查异常: 除了 Error 和RuntimeException 以及他们的子类,java强制要求程序员为这样的异常做预处理工作 ,try..catch..finally)这样处理。要么throws 子句声明抛出来,否则编译不过,这样的异常一般由程序的运行的环境导致的。因为程序可能被运行在各种未知的环境下,而程序员无法干预用户如何使用他编写的程序,于是程序员就应该为这样的异常时刻准备着 如SQLException , IOException,ClassNotFoundException 等

2.springboot 全局异常处理

创建 response类

@Data
public class Response<T> {
    private Integer code;
    private String message;
    private T data;

    public Response() {
    }

    public Response(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public Response(Integer code, String message) {
        this.code = code;
        this.message = message;
        this.data = null;
    }

}

创建自定义异常类

public class CustomException extends Exception {
   private static final long serialVersionUID = 3256874491192825748L;

    private int code;

    public CustomException() {
        super();
    }

    public CustomException(int code, String message) {
        super(message);
        this.setCode(code);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
    
}

方法1

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {


        log.error("request : {}", request.toString());

        Response response = new Response(status.value(), status.getReasonPhrase());

        return new ResponseEntity(response,status);
    }


    @ExceptionHandler(Exception.class)
    protected Response onException(Exception ex) {

        log.error("Exception : {}", ex.toString());

        return new Response(500, "Exception fail");
    }

    @ExceptionHandler(RuntimeException.class)
    protected Response onException(RuntimeException ex) {

        log.error("RuntimeException : {}", ex.toString());

        return new Response(500, "RuntimeException fail");
    }

    @ExceptionHandler(CustomException.class)
    public Response onException(CustomException ex) {

        log.error("CustomException : {}", ex.getMessage());

        return new Response(500, "CustomException fail");
    }


}

方法2

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler({Exception.class})
    public Response onException(Exception ex) {

        log.error("exception : {}", ex.getMessage());

        return new Response(500, "fail");
    }

    @ExceptionHandler(RuntimeException.class)
    public Response onException(RuntimeException ex) {

        log.error("RuntimeException : {}", ex.getMessage());

        return new Response(500, "RuntimeException fail");
    }

    @ExceptionHandler(CustomException.class)
    public Response onException(CustomException ex) {

        log.error("CustomException : {}", ex.getMessage());

        return new Response(500, "CustomException fail");
    }


}

总结:

继承 ResponseEntityExceptionHandler 类的来实现全局异常处理比较好。因为springMV内部封装了一层
http标准的状态码,当发生异常的时候 header中的状态码也会相应的改变而不是一直是200.

异常匹配的顺序:
当我们通过 @ExceptionHandler 来精确匹配某个异常类的时候,发生异常的时候,会直接走相应的匹配的异常处理流程,当我们没有精确匹配的时候,程序会一直找父类,如果没有就一直找祖父类。总结的讲就是就近原则来处理异常

https://juejin.cn/post/6882902652556935181
https://www.jianshu.com/p/02d334c3a8e8?utm_source=oschina-app
https://juejin.cn/post/6844903998579802126
https://www.cnblogs.com/lulipro/p/7504267.html

相关文章

网友评论

      本文标题:springboot全局异常处理

      本文链接:https://www.haomeiwen.com/subject/fjwpnktx.html