Spring 异常处理

目录

    SpringBoot 中有一个 ControllerAdvice 的注解,使用该注解表示开启了全局异常的捕获,我们只需在自定义一个方法使用 ExceptionHandler 注解然后定义捕获异常的类型即可对这些捕获的异常进行统一的处理。

    【示例】

    • 封装一个返回体

    这里,我们需要先定义一个全局异常类 BaseException,然后再定义一个通用返回体:

    @Data
    public class GenericResponseBody {
    private String msg;
    private String code;
    public ErrorResponse(String code, String msg) {
    this.code = code;
    this.msg = msg;
    }
    public static GenericResponseBody fail(Exception e) {
    this.code = 10001;
    this.msg = e.msg();
    }
    public static GenericResponseBody fail(BaseException e) {
    this.code = e.getCode();
    this.msg = e.msg();
    }
    }
    • 定义一个全局异常处理器
    @ControllerAdvice(assignableTypes = {ExceptionController.class})
    @ResponseBody
    public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<GenericResponseBody> baseExceptionHandler(BaseException e) {
    return ResponseEntity.status(200).body(GenericResponseBody.fail(e));
    }
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<GenericResponseBody> exceptionHandler(Exception e) {
    return ResponseEntity.status(400).body(GenericResponseBody.fail(e));
    }
    }

    参考:

    本文作者:LARRY1024

    本文链接:https://www.cnblogs.com/larry1024/p/17775259.html

    版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

    posted @   LARRY1024  阅读(63)  评论(0编辑  收藏  举报
    点击右上角即可分享
    微信分享提示
    💬
    评论
    📌
    收藏
    💗
    关注
    👍
    推荐
    🚀
    回顶
    收起
    1. 1 404 not found REOL
    404 not found - REOL
    00:00 / 00:00
    An audio error has occurred.