学习篇:基于springboot2.1.x的统一错误处理方式

本文深入探讨SpringBoot中三种异常处理方式:自定义静态异常页面、继承BasicErrorController及利用ControllerAdvice。详细介绍每种方法的实现步骤与关键代码,为开发者提供全面的异常处理指南。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、springBoot统一异常处理方式

官网参考地址:https://docs.spring.io/spring-boot/docs/2.1.7.RELEASE/reference/htmlsingle/#boot-features-error-handling
搜索关键词:Error Handling

  • 方式一 静态异常页面
    自定义静态异常页面,又分为两种,第一种 是使用 HTTP 响应码来命名页面,例如 404.html、405.html、500.html …,另一种就是直接定义一个4xx.html,表示400-499 的状态都显示这个异常页面,5xx.html 表示 500-599 的状态显示这个异常页面。
  1. 在resources目录下新建public目录下添加类似5xx.html自定义渲染页面【官网提供的路径】。
  2. 在resources目录下新建static目录下添加类似5xx.html自定义渲染页面。
    路径:
resources/public/error/5xx.html 或者
resources/static/error/5xx.html

如果两者都存在会先找static目录下的异常,查找顺序。
在这里插入图片描述
在这里插入图片描述

  • 方式二 继承BasicErrorController
    在这里插入图片描述

整体涉及到的类
在这里插入图片描述

  1. 定义MyErrorController 重写构造方法,重写getErrorAttributes方法
/**
 * @ClassName MyErrorController
 * @Description 自定义异常
 * @Author eastern
 * @Date 2019/8/15 下午3:57
 * @Version 1.0
 **/
public class MyErrorController extends BasicErrorController {


    public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }


    @Override
    protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        Map<String, Object> attrs = super.getErrorAttributes(request, includeStackTrace);
        attrs.remove("timestamp");
        attrs.remove("status");
        attrs.remove("error");
        attrs.remove("path");
        String errorCode = attrs.get("message").toString();
        ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode);
        attrs.put("code", attrs.get("message"));
        attrs.put("message", errorEnum.getMessage());
        attrs.put("canRetry", errorEnum.isCanRetry());

        return attrs;
    }

}

  1. 定义ErrorConfiguration 配置
    参看:ErrorMvcAutoConfiguration
    在这里插入图片描述
/**
 * @ClassName ErrorConfiguration
 * @Description 错误处理相关类
 * @Author eastern
 * @Date 2019/8/15 下午4:08
 * @Version 1.0
 **/
@Configuration
public class ErrorConfiguration {

    @Bean
    public MyErrorController basicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties, DispatcherServletPath dispatcherServletPath,
                                                  ObjectProvider<ErrorViewResolver> errorViewResolvers) {
        return new MyErrorController(errorAttributes, serverProperties.getError(), errorViewResolvers.orderedStream().collect(Collectors.toList()));
    }
}

  1. 定义错误枚举

/**
 * 错误枚举类
 */
public enum ErrorEnum {

    ID_NOT_NULL("0001", "编号不能为空", false),
    UNKNOWN("9999", "未知异常", false);

    private String code;
    private String message;
    private boolean canRetry;

    ErrorEnum(String code, String message, boolean canRetry){
        this.code = code;
        this.message = message;
        this.canRetry = canRetry;
    }

    public static ErrorEnum getByCode(String code){
        for (ErrorEnum errorEnum: ErrorEnum.values()) {
            if(errorEnum.code.equals(code)){
                return errorEnum;
            }
        }
        return UNKNOWN;
    }

    public String getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public boolean isCanRetry() {
        return canRetry;
    }
}
  • 方式三 利用ControllerAdvice
    ControllerAdvice在Controller上包了一层,增强的Controller,但是如果ControllerAdvice里再出现异常,会进入到自定义的ErrorController
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值