Spring Boot 自定义异常处理

2022-10-05 10:08:23

自定义异常数据

@Bean@ConditionalOnMissingBean(value= ErrorAttributes.class, search= SearchStrategy.CURRENT)public DefaultErrorAttributeserrorAttributes(){returnnewDefaultErrorAttributes();}

以上这一段源代码的意思是,如果存在ErrorAttributes类则使用本来存在的类,不存在就使用默认的DefaultErrorAttributes类来定义异常数据,所以要自定义就需要继承DefaultErrorAttributes 类来定制自己的类

@ComponentpublicclassMyErrorAttributesextendsDefaultErrorAttributes{@Overridepublic Map<String, Object>getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options){
        Map<String, Object> map=super.getErrorAttributes(webRequest, options);if((Integer) map.get("status")==404){
            map.put("message","找不到页面");}return map;}}

前端页面:

<!DOCTYPE html><htmllang="en"xmlns:th="http://www.thymeleaf.org"><head><metacharset="UTF-8"><title>404Title</title></head><body><tableborder="1"align="solid"><tr><td>path</td><tdth:text="${path}"></td></tr><tr><td>error</td><tdth:text="${error}"></td></tr><tr><td>message</td><tdth:text="${message}"></td></tr><tr><td>timestamp</td><tdth:text="${timestamp}"></td></tr><tr><td>status</td><tdth:text="${status}"></td></tr></table></body></html>

结果:
在这里插入图片描述

自定义异常页面

在这里插入图片描述
如果存在ErrorViewResolver类则使用本来存在的类,不存在就使用默认的DefaultErrorViewResolver类来定义异常数据,所以要自定义就需要继承DefaultErrorViewResolver类来定制自己的类来返回错误页面

自定义类:

@ComponentpublicclassMyErrorViewResolverextendsDefaultErrorViewResolver{publicMyErrorViewResolver(ApplicationContext applicationContext, WebProperties.Resources resources){super(applicationContext, resources);}@Overridepublic ModelAndViewresolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model){
        Map<String,Object> map=newHashMap<>();if((Integer) model.get("status")==500){
            map.putAll(model);
            map.put("message","服务器端出现错误");}
        ModelAndView view=newModelAndView("dong/521", map);return  view;}}

前端页面:
在这里插入图片描述

<!DOCTYPE html><htmllang="en"xmlns:th="http://www.thymeleaf.org"><head><metacharset="UTF-8"><title>404Title</title></head><body><h1>521.html</h1><tableborder="1"align="solid"><tr><td>path</td><tdth:text="${path}"></td></tr><tr><td>error</td><tdth:text="${error}"></td></tr><tr><td>message</td><tdth:text="${message}"></td></tr><tr><td>timestamp</td><tdth:text="${timestamp}"></td></tr><tr><td>status</td><tdth:text="${status}"></td></tr></table></body></html>
  • 作者:泠青沼~
  • 原文链接:https://blog.csdn.net/m0_46635265/article/details/123172589
    更新时间:2022-10-05 10:08:23