SpringBoot——Web开发三(错误处理机制)

本文介绍了SpringBoot的默认错误处理机制,包括浏览器下默认的错误页面和JSON响应。详细阐述了如何定制错误响应,包括自定义错误页面和错误的JSON数据。在定制错误页面时,可通过设置错误状态码.html文件于模板引擎的error目录下,或者在静态资源目录下查找。自定义错误的JSON数据则需创建异常处理类并实现ErrorController接口,通过ErrorAttributes获取并定制返回数据。
摘要由CSDN通过智能技术生成

1.SpringBoot默认的错误处理机制

1.1默认效果

1.浏览器,会返回一个默认的错误页面

2.如果是其他客户端,默认响应一个JSON数据

1.2 原理

可以参照ErrorMvcAutoConfiguration,错误处理的自动配置,这个给容器中添加了以下组件。

1.DefaultErrorAttributes

//帮我们共享信息 
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Map<String, Object> errorAttributes = this.getErrorAttributes(webRequest, options.isIncluded(Include.STACK_TRACE));
        if (this.includeException != null) {
            options = options.including(new Include[]{Include.EXCEPTION});
        }

        if (!options.isIncluded(Include.EXCEPTION)) {
            errorAttributes.remove("exception");
        }

        if (!options.isIncluded(Include.STACK_TRACE)) {
            errorAttributes.remove("trace");
        }

        if (!options.isIncluded(Include.MESSAGE) && errorAttributes.get("message") != null) {
            errorAttributes.put("message", "");
        }

        if (!options.isIncluded(Include.BINDING_ERRORS)) {
            errorAttributes.remove("errors");
        }

        return errorAttributes;
    }

    /** @deprecated */
    @Deprecated
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = new LinkedHashMap();
        errorAttributes.put("timestamp", new Date());
        this.addStatus(errorAttributes, webRequest);
        this.addErrorDetails(errorAttributes, webRequest, includeStackTrace);
        this.addPath(errorAttributes, webRequest);
        return errorAttributes;
    }

2.BasicErrorController:处理默认/error请求

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController 

在其方法中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值