Springboot自定义全局异常处理

目录

ErrorController

@ControllerAdvice+@ExceptionHandler 


ErrorController

BasicErrorController是Spring Boot中默认提供的用于处理基本错误的控制器。它实现了ErrorController接口,用于处理在应用程序中发生的错误,例如404 Not Found等。此种方式是通过请求转发实现的,出现异常时,会转发到请求到/error,该接口对异常进行处理返回,是最符合全局异常处理的。

项目需要的响应信息都是自定义统一格式的JSON(code、msg、data),因此可以继承ErrorController接口实现异常处理的自定义。

响应实体类:

@Data
@ToString
public class Result<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    //业务码,比如成功、失败、权限不足等 code,可自行定义

    private int resultCode;
    //返回信息,后端在进行业务处理后返回给前端一个提示信息,可自行定义

    private String message;
    //数据结果,泛型,可以是列表、单个对象、数字、布尔值等

    private T data;

    public Result() {
    }

    public Result(int resultCode, String message) {
        this.resultCode = resultCode;
        this.message = message;
    }

}

继承ErrorController接口实现异常处理的自定义,代码如下:


@RestController
public class CustomErrorController implements ErrorController {
    private ErrorAttributes errorAttributes;

    public CustomErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    @RequestMapping("/error")
    public Result handleError(HttpServletRequest request) {
        // 获取异常信息
//        Map<String, Object> errorAttributes = this.errorAttributes.getErrorAttributes(new ServletWebRequest(request),true);

        // 获取异常信息的状态码
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        // 获取异常信息的详细信息
        Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
        String errorMessage = (throwable != null ? throwable.getMessage() : "Unknown error");
        return new Result(statusCode,errorMessage);
    }


    public String getErrorPath() {
        return "/error";
    }
}

@ControllerAdvice+@ExceptionHandler 

继承ErrorController接口实现异常处理的方法,对于自定义业务错误码code不好得到,有时候我们会自定义一些异常信息,比如:

public class AException extends Exception{
    public AException() {
        super();
    }

    public AException(String message) {
        super(message);
    }
}

@ControllerAdvice注解用于声明一个全局控制器建言(advice)。它是一个组件类,专门用于处理全局异常和全局数据绑定。通常,你可以在这个类中定义多个@ExceptionHandler方法,每个方法处理不同类型的异常。代码如下:

@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Result AException(Exception e, HttpServletRequest request,HttpServletResponse response){
        Result result=new Result();
        result.setResultCode(response.getStatus());

        if(e instanceof AException){
            result.setResultCode(1000);
            result.setMessage("AException error");
        }

        result.setMessage(e.getMessage());
        return result;
    }
}

但是它也有个缺点,就是处理不了过滤器等抛出的异常。因此在全局异常处理方案中,推荐使用ErrorController+@ControllerAdvice+@ExceptionHandler 的实现方案,Controller抛出了异常,被异常处理器(@ControllerAdvice+@ExceptionHandler)首先处理。过滤器抛出异常,由基于请求转发的方式(ErrorController)处理异常。

注意:本人Springboot版本 2.7.12

  • 11
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

山河亦问安

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值