SpringBoot(六)——错误处理机制

1. SpringBoot 默认错误处理机制

当访问一个不存在的页面,或者程序抛出异常时

默认效果:

  • 浏览器,返回一个默认的错误页面, 注意看浏览器发送请求的请求头:
    在这里插入图片描述
  • 其他客户端,返回json数据,注意看请求头
    在这里插入图片描述

查看org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration源码,这里是springboot错误处理的自动配置信息

主要给日容器中注册了以下组件:

  • ErrorPageCustomizer 系统出现错误以后来到error请求进行处理;相当于(web.xml注册的错误页面规则)
  • BasicErrorController 处理/error请求
  • DefaultErrorViewResolver 默认的错误视图解析器
  • DefaultErrorAttributes 错误信息
  • defaultErrorView 默认错误视图

ErrorPageCustomizer

@Bean
    public ErrorMvcAutoConfiguration.ErrorPageCustomizer errorPageCustomizer(DispatcherServletPath dispatcherServletPath) {
        return new ErrorMvcAutoConfiguration.ErrorPageCustomizer(this.serverProperties, dispatcherServletPath);
    }

ErrorPageCustomizer 类

static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered {
        private final ServerProperties properties;
        private final DispatcherServletPath dispatcherServletPath;

        protected ErrorPageCustomizer(ServerProperties properties, DispatcherServletPath dispatcherServletPath) {
            this.properties = properties;
            this.dispatcherServletPath = dispatcherServletPath;
        }
		
		//注册错误页面
        public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
            getPath()获取到的是"/error",见下图
            ErrorPage errorPage = new ErrorPage(this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
            errorPageRegistry.addErrorPages(new ErrorPage[]{errorPage});
        }

        public int getOrder() {
            return 0;
        }
    }

在这里插入图片描述

一旦系统出现4xx 或5xx之类的错误,ErrorPageCustomizer 就会生效(定制错误的响应规则),就会来到/error请求,就会被BasicErrorController 处理

BasicErrorController

@Bean
    @ConditionalOnMissingBean(
        value = {ErrorController.class},
        search = SearchStrategy.CURRENT
    )
    public BasicErrorController basicErrorController(ErrorAttributes errorAttributes, ObjectProvider<ErrorViewResolver> errorViewResolvers) {
        return new BasicErrorController(errorAttributes, this.serverProperties.getError(), (List)errorViewResolvers.orderedStream().collect(Collectors.toList()));
    }

处理/error 请求

@Controller
/**
  *	使用配置文件中server.error.path配置
  * 如果server.error.path没有配置使用error.path
  * 如果error.path也没有配置就使用/error
  */
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {

errorHtml 和 erro方法
在这里插入图片描述

这两个方法,errorhtml用于浏览器请求响应html页面,error用于其他客户端请求响应json数据,主要是根据请求头来区分是浏览器发的请求还是客户端发送的请求,来调用相应的方法

处理浏览器请求的方法 中,modelAndView存储到哪个页面的页面地址和页面内容数据

看一下调用的resolveErrorView方法

protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
        Iterator var5 = this.errorViewResolvers.iterator();

        ModelAndView modelAndView;
        do {
            if (!var5.hasNext()) {
                return null;
            }

            ErrorViewResolver resolver = (ErrorViewResolver)var5.next();
            //遍历所有的errorViewResolvers,得到一个modelAndView对象
            modelAndView = resolver.resolveErrorView(request, status, model);
        } while(modelAndView == null);

        return modelAndView;
    }

ErrorViewResolver从哪里来的呢?

已经在容器中注册了一个DefaultErrorViewResolver

DefaultErrorViewResolver

static class DefaultErrorViewResolverConfiguration {
        private final ApplicationContext applicationContext;
        private final ResourceProperties resourceProperties;

        DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext, ResourceProperties resourceProperties) {
            this.applicationContext = applicationContext;
            this.resourceProperties = resourceProperties;
        }

        @Bean //注册默认错误视图解析器
        @ConditionalOnBean({DispatcherServlet.class})
        @ConditionalOnMissingBean({ErrorViewResolver.class})
        DefaultErrorViewResolver conventionErrorViewResolver() {
            return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties);
        }
    }
}

BasicErrorController 中调用了resolveErrorView,这个方法遍历了所有的errorViewResolvers,并且调用DefaultErrorViewResolver 类
中的resolveErrorView(request, status, model)方法获取modelAndView对象。下面来看DefaultErrorViewResolver 类的resolveErrorView方法

public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
          //把状态码和model传过去获取视图对象
        ModelAndView modelAndView = this.resolve(String.valueOf(status.value()), model);
        //上面没有获取到视图对象就把状态码替换再再找,以4开头的替换为4xx,5开头替换为5xx,见下文(如果定制错误响应)
        if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
            modelAndView = this.resolve((String)SERIES_VIEWS.get(status.series()), model);
        }

        return modelAndView;
    }

    private ModelAndView resolve(String viewName, Map<String, Object> model) {
    	//viewName传过来的是状态码,例:/error/404
        String errorViewName = "error/" + viewName;
        TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
          //模板引擎可以解析这个页面地址就用模板引擎解析 
        return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);
    }

如果模板引擎不可用,就调用resolveResource方法获取视图

private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
     //获取的是静态资源文件夹,{"classpath:/META-INF/resources/", "classpath:/resources/",
     // "classpath:/static/", "classpath:/public/"};
     String[] var3 = this.resourceProperties.getStaticLocations();
     int var4 = var3.length;

     for(int var5 = 0; var5 < var4; ++var5) {
         String location = var3[var5];

         try {
             Resource resource = this.applicationContext.getResource(location);
             //在静态资源文件夹下找对应的错误页面
             resource = resource.createRelative(viewName + ".html");
             //如果存在,就返回modelAndView对象
             if (resource.exists()) {
                 return new ModelAndView(new DefaultErrorViewResolver.HtmlResourceView(resource), model);
             }
         } catch (Exception var8) {
         }
     }

     return null;
 }

2. 如何定制错误响应页面

2.1 定制错误页面

  1. 有模板引擎的情况下,将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的 error文件夹下,发生此状态码的错误就会来到这里找对应的页面;

比如我们在template文件夹下创建error/404.html,当浏览器请求是404错误,就会使用我们创建的404.html页面响应,如果是其他状态码错误,还是使用默认的视图,但是如果404.html没有找到,就会替换成4XX.html再查找一次,如果有相应的4xx.html,有的话就使用,没有的话,就会使用默认视图。看DefaultErrorViewResolver中的静态代码块

static {
        Map<Series, String> views = new EnumMap(Series.class);
        //Series是枚举类
        views.put(Series.CLIENT_ERROR, "4xx");
        views.put(Series.SERVER_ERROR, "5xx");
        SERIES_VIEWS = Collections.unmodifiableMap(views);
    }

再看解析方法,DefaultErrorViewResolver类中的resolveErrorView

public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
       //把状态码和model传过去获取视图对象
        ModelAndView modelAndView = this.resolve(String.valueOf(status.value()), model);
         //上面没有获取到视图对象就把状态码替换再再找,以4开头的替换为4xx,5开头替换为5xx
        if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
            modelAndView = this.resolve((String)SERIES_VIEWS.get(status.series()), model);
        }

        return modelAndView;
    }

页面可以获取哪些数据?

**DefaultErrorAttributes **

再看一下BasicErrorController的errorHtml方法

@RequestMapping(
        produces = {"text/html"}
    )
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = this.getStatus(request);
        //model的数据
        Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
        return modelAndView != null ? modelAndView : new ModelAndView("error", model);
    }

看一下调用的this.getErrorAttributes()方法

protected Map<String, Object> getErrorAttributes(HttpServletRequest request, ErrorAttributeOptions options) {
        WebRequest webRequest = new ServletWebRequest(request);
        return this.errorAttributes.getErrorAttributes(webRequest, options);
    }

再看 this.errorAttributes.getErrorAttributes()方法, this.errorAttributes是接口ErrorAttributes类型,实现类就一个DefaultErrorAttributes,看一下DefaultErrorAttributesgetErrorAttributes()方法

@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;
    }
  • timestamp:时间戳
  • status:状态码
  • error:错误提示
  • exception:异常对象
  • message:异常消息
  • errors:JSR303数据校验的错误都在这里

2.0以后默认是不显示exception的,需要在配置文件中开启

server.error.include-exception=true

原因是
在这里插入图片描述
注册时在这里插入图片描述

这些数据,都可以在错误页面中使用thymeleaf的语法获取到。比如在4xx页面中写

<h1>status:[[${status}]]</h1>
<h1>time:[[${timestamp}]]</h1>

只要是状态码是4开头的,页面中都能显示状态码和时间。

  1. 没有模板引擎(模板引擎找不到这个错误页面),就会在静态资源文件夹下找,这样的话,错误页面中的信息就无法获得;
  2. 如果以上都没有找到错误页面,就是默认来到SpringBoot默认的错误提示页面;

2.2 定制错误的json数据

springboot做了自适应效果,浏览器访问响应错误页面。客户端访问响应错误信息的json数据

  1. 第一种方法,定义全局异常处理器类,并注入到容器中,捕获到异常返回json格式的数据

@ControllerAdvice //自定义异常处理器
public class MyExceptionHandler {
    @ResponseBody //将结果变成json格式
    //只要发生UserNotExistsException异常,就会执行这个方法
    @ExceptionHandler(UserNotExistsException.class)
    public Map<String, Object> handleException(Exception e) {
        Map<String, Object> map = new HashMap<>();
        map.put("code","user.notExists");
        map.put("message", e.getMessage());
        return map;
    }
}

访问http://localhost:8080/hello?user=aaa

@Controller
public class HelloController {
    @ResponseBody
    @RequestMapping("/hello")
    public String hello(@RequestParam("user") String user){
        if(user.equals("aaa")) {
            throw new UserNotExistsException();
        }
        return "hello";
    }
}

这样的话,不管是浏览器访问还是客户端访问都是响应json数据,就没有了自适应效果

  1. 使用SpringBoot提供的BasicErrorController来实现自适应效果,捕获到异常后转发到/error
@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        Map<String, Object> map = new HashMap(2);
        map.put("code", "100011");
        map.put("msg", e.getMessage());
        return "forward:/error";
    }
}

访问localhost:8080/hello?str=hi,但这样异常被我们捕获然后转发,显示的状态码就是200,所以在转发之前还要设置一下状态码

@ExceptionHandler(UserNotExistsException.class)
    public String handleException(Exception e, HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        //设置状态码
        request.setAttribute("javax.servlet.error.status_code", 500);
        map.put("code","user.notExists");
        map.put("message", e.getMessage());
        //转发到/error
        return "forward:/error";
    }

但是设置的数据就没有用了,只能使用默认的

由上面我们已经知道数据的来源是调用DefaultErrorAttributesgetErrorAttributes方法得到的,而这个DefaultErrorAttributes是在ErrorMvcAutoConfiguration配置类中注册的,并且注册之前会检查容器中是否已经拥有ErrorAttributes,没有才会注册。


    @Bean
    @ConditionalOnMissingBean(
        value = {ErrorAttributes.class},
        search = SearchStrategy.CURRENT
    )
    public DefaultErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes();
    }

  1. 所以我们可以只要实现ErrorAttributes接口或者继承DefaultErrorAttributes类,并且重写getErrorAttributes()方法即可,然后注册到容器中就行了
@Component //给容器中加入自定义的ErrorAttribute
public class MyErrorAttribute extends DefaultErrorAttributes {

    @Override //在错误页面中添加自己定义的错误信息
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        //调用父类的方法获取默认的数据
        Map<String, Object> map = super.getErrorAttributes(webRequest,options);
       //添加自定义的数据
        map.put("author","ewen");
        //在MyExceptionHandler中处理了异常,添加异常处理的信息到错误页面,
        Map<String, Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", 0);
        map.put("ext", ext);
        return map;
    }
}

参考:SpringBoot权威教程


版权声明:本文为weixin_43691723原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。