默认情况下,Spring Boot提供/error处理所有错误的映射
对于机器客户端(例如PostMan),它将生成JSON响应,其中包含错误,HTTP状态和异常消息的详细信息(如果设置了拦截器,需要在请求头中塞入Cookie相关参数)
对于浏览器客户端,响应一个“ whitelabel”错误视图,以HTML格式呈现相同的数据
另外,templates下面error文件夹中的4xx,5xx页面会被自动解析
那么Spring Boot是怎么实现上述的错误页相关功能的呢?
我们又要来找一下相关源码进行分析了
首先我们先了解一个概念:@Bean配置的类的默认id是方法的名称,但是我们可以通过value或者name给这个bean取别名,两者不可同时使用
我们进入ErrorMvcAutoConfiguration
,看这个类名应该是和错误处理的自动配置有关,我们看下这个类做了什么
DefaultErrorAttributes
,id为errorAttributes
的bean(管理错误信息,如果要自定义错误页面打印的字段,就自定义它),这个类实现了ErrorAttributes, HandlerExceptionResolver(异常处理解析器接口), Ordered三个接口@Bean
@ConditionalOnMissingBean(
value = {ErrorAttributes.class},
search = SearchStrategy.CURRENT
)
public DefaultErrorAttributes errorAttributes() {
return new DefaultErrorAttributes();
}
点进去后发现,这个类是和我们响应页面中的message、error等字段有关
basicErrorController
的控制器bean(管理错误相应逻辑,不想返回json或者错误视图,就自定义它)@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()));
}
DefaultErrorViewResolver
,id为conventionErrorViewResolver
的bean(管理错误视图跳转路径,如果要改变跳转路径,就自定义它)@Configuration(
proxyBeanMethods = false
)
@EnableConfigurationProperties({WebProperties.class, WebMvcProperties.class})
static class DefaultErrorViewResolverConfiguration {
private final ApplicationContext applicationContext;
private final Resources resources;
DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext, WebProperties webProperties) {
this.applicationContext = applicationContext;
this.resources = webProperties.getResources();
}
@Bean
@ConditionalOnBean({DispatcherServlet.class})
@ConditionalOnMissingBean({ErrorViewResolver.class})
DefaultErrorViewResolver conventionErrorViewResolver() {
return new DefaultErrorViewResolver(this.applicationContext, this.resources);
}
}
这个类中,解释了为什么前面会根据不同的状态码转向不同的错误页
WhitelabelErrorViewConfiguration
,它与错误视图配置相关,这个类中声明了一个id为error的视图对象提供给basicErrorController
中使用,还定义了视图解析器BeanNameViewResolver
,它会根据返回的视图名作为组件的id去容器中找View对象@Configuration(
proxyBeanMethods = false
)
@ConditionalOnProperty(
prefix = "server.error.whitelabel",
name = {"enabled"},
matchIfMissing = true
)
@Conditional({ErrorMvcAutoConfiguration.ErrorTemplateMissingCondition.class})
protected static class WhitelabelErrorViewConfiguration {
private final ErrorMvcAutoConfiguration.StaticView defaultErrorView = new ErrorMvcAutoConfiguration.StaticView();
protected WhitelabelErrorViewConfiguration() {
}
@Bean(
name = {"error"}
)
@ConditionalOnMissingBean(
name = {"error"}
)
public View defaultErrorView() {
return this.defaultErrorView;
}
@Bean
@ConditionalOnMissingBean
public BeanNameViewResolver beanNameViewResolver() {
BeanNameViewResolver resolver = new BeanNameViewResolver();
resolver.setOrder(2147483637);
return resolver;
}
}
private static class StaticView implements View {
private static final MediaType TEXT_HTML_UTF8;
private static final Log logger;
private StaticView() {
}
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (response.isCommitted()) {
String message = this.getMessage(model);
logger.error(message);
} else {
response.setContentType(TEXT_HTML_UTF8.toString());
StringBuilder builder = new StringBuilder();
Object timestamp = model.get("timestamp");
Object message = model.get("message");
Object trace = model.get("trace");
if (response.getContentType() == null) {
response.setContentType(this.getContentType());
}
...
为了了解Spring Boot的异常处理流程,我们写一个demo进行debug
首先写一个会发生算术运算异常的接口/test_error
/**
* 测试报错信息
* @return 跳转错误页面
*/
@GetMapping(value = "/test_error")
public String testError() {
int a = 1/0;
return String.valueOf(a);
}
然后放置一个错误页面5xx.html于templates下的error文件夹中
DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content="">
<meta name="author" content="ThemeBucket">
<link rel="shortcut icon" href="#" type="image/png">
<title>500 Pagetitle>
<link href="css/style.css" rel="stylesheet">
<link href="css/style-responsive.css" rel="stylesheet">
head>
<body class="error-page">
<section>
<div class="container ">
<section class="error-wrapper text-center">
<h1><img alt="" src="images/500-error.png">h1>
<h2>OOOPS!!!h2>
<h3 th:text="${message}">Something went wrong.h3>
<p class="nrml-txt" th:text="${trace}">Why not try refreshing you page? Or you can <a href="#">contact our supporta> if the problem persists.p>
<a class="back-btn" href="index.html" th:text="${status}"> Back To Homea>
section>
div>
section>
<script src="js/jquery-1.10.2.min.js">script>
<script src="js/jquery-migrate-1.2.1.min.js">script>
<script src="js/bootstrap.min.js">script>
<script src="js/modernizr.min.js">script>
body>
html>
然后我们开启debug模式,发送请求
首先,我们的断点还是来到DispatcherServlet
类下的doDispatch()
方法
经过mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
调用目标方法之后,他会返回相关错误信息,并将其塞入dispatchException这个对象
然后调用this.processDispatchResult(processedRequest, response, mappedHandler, mv, (Exception)dispatchException);
处理调度结果
然后他会在processDispatchResult()
中经过判断是否存在异常,异常不为空,调用processHandlerException()
方法,这里它会遍历系统中所有的异常处理解析器,哪个解析器返回结果不为null,就结束循环
在调用DefaultErrorAttributes
时,它会将错误中的信息放入request请求域中(我们后面模板引擎页面解析会用到)
遍历完所有解析器,我们发现他们都不能返回一个不为空的ModelAndView
对象,于是它会继续抛出异常
当系统发现没有任何人能处理这个异常时,底层就会发送 /error 请求,它就会被我们上面介绍的BasicErrorController
下的errorHtml()
方法处理
这个方法会通过ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
去遍历系统中所有的错误视图解析器,如果调用解析器的resolveErrorView()
方法返回结果不为空就结束循环
系统中只默认注册了一个错误视图解析器,也就是我们上面介绍的DefaultErrorViewResolver
,跟随debug断点我们得知,这个解析器会把error+响应状态码
作为错误页的地址,最终返回给我们的视图地址为error/5xx.html
error下的4xx.html和5xx.html,根据我们上面了解的DefaultErrorViewResolver
类可以,它的resolveErrorView()
方法在进行错误页解析时,如果有精确的错误状态码页面就匹配精确,没有就找 4xx.html,如果都没有就转到系统默认的错误页
package com.decade.exception;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
@Slf4j
public class MyExceptionHandler {
// 指定该方法处理某些指定异常,@ExceptionHandler的value可以是数组,这里我们指定该方法处理数学运算异常和空指针异常
@ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})
public String handleArithmeticException(Exception exception) {
log.error("异常信息为:{}", exception);
// 打印完错误信息后,返回登录页
return "login";
}
}
我们还是使用上面的会发生算术运算异常的接口/test_error
进行测试
请求接口后发现,页面跳转到登录页了
为什么没有再走到5xx.html呢?
因为@ControllerAdvice+@ExceptionHandler的底层是ExceptionHandlerExceptionResolver
来处理的
这样在进入DispatcherServlet
类下的processHandlerException()
方法时,就会调用ExceptionHandlerExceptionResolver
这个异常处理解析器,从而跳转到我们自己创建的异常处理类进行异常处理,然后返回不为null的ModelAndView对象给它,终止遍历,不会再发送/error
请求
package com.decade.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
// code对应错误码,reason对应message
@ResponseStatus(code = HttpStatus.METHOD_NOT_ALLOWED, reason = "自定义异常")
public class CustomException extends RuntimeException {
public CustomException() {
}
public CustomException(String message) {
super(message);
}
}
然后写一个接口去抛出自定义异常
/**
* 测试报错信息
* @return 跳转错误页面
*/
@GetMapping(value = "/test_responseStatus")
public String testResponseStatus(@RequestParam("param") String param) {
if ("test_responseStatus".equals(param)) {
throw new CustomException();
}
return "main";
}
最后我们调用接口,可以得到,跳转到了4xx.html,但是状态码和message都和我们自己定义的匹配
那么原理是什么呢?我们还是从DispatcherServlet
类下的processHandlerException()
方法开始看
当我们抛出自定义异常时,由于前面@ControllerAdvice+@ExceptionHandler修饰的类没有指定处理这个异常,所以循环走到下一个异常处理解析器ResponseStatusExceptionResolver
我们分析一下这里的代码
@Nullable
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {
try {
if (ex instanceof ResponseStatusException) {
return this.resolveResponseStatusException((ResponseStatusException)ex, request, response, handler);
}
// 由于我们自定义异常类使用了@ResponseStatus注解修饰,所以我们这里获取到的status信息不为空
ResponseStatus status = (ResponseStatus)AnnotatedElementUtils.findMergedAnnotation(ex.getClass(), ResponseStatus.class);
if (status != null) {
return this.resolveResponseStatus(status, request, response, handler, ex);
}
...
protected ModelAndView resolveResponseStatus(ResponseStatus responseStatus, HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) throws Exception {
// 获取@ResponseStatus注解的code和reason作为状态码和message
int statusCode = responseStatus.code().value();
String reason = responseStatus.reason();
return this.applyStatusAndReason(statusCode, reason, response);
}
protected ModelAndView applyStatusAndReason(int statusCode, @Nullable String reason, HttpServletResponse response) throws IOException {
if (!StringUtils.hasLength(reason)) {
response.sendError(statusCode);
} else {
String resolvedReason = this.messageSource != null ? this.messageSource.getMessage(reason, (Object[])null, reason, LocaleContextHolder.getLocale()) : reason;
// 发送/error请求,入参为@ResponseStatus注解的code和reason
response.sendError(statusCode, resolvedReason);
}
// 返回一个modelAndView
return new ModelAndView();
}
经过debug我们知道,ResponseStatusExceptionResolver
这个异常处理解析器返回了一个空的ModelAndView对象给我们,而且还通过response.sendError(statusCode, resolvedReason);
发送了/error请求
这样就又走到了上面的第三节处理/error请求的流程中,从而带着我们@ResponseStatus注解的code和reason跳转到了4xx.html页面,这样就能解释为什么4xx.html页面中的状态码和message都是我们自定义的了
DefaultHandlerExceptionResolver
这个异常处理解析器进行处理的doResolveException()
方法得知,它最后也会发送/error
请求,从而转到4xx.html或者5xx.html页面使用@Component注解,并实现HandlerExceptionResolver
接口来自定义一个异常处理解析器
package com.decade.exception;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
// 将优先级提到第一位,Order越小,优先级越高,所以我们这里设置int的最小值
@Order(Integer.MIN_VALUE)
@Component
public class CustomExceptionHandler implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
try {
response.sendError(500, "自己定义的异常");
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView();
}
}
当我们把优先级提到最高时,前面的那些异常处理解析器都会失效,这时我们的自定义异常处理解析器可以作为默认的全局异常处理规则
值得注意的是,当代码走到response.sendError
时,就会触发/error
请求,当你的异常没有人能处理时,也会走tomcat底层触发response.sendError
,发送/error
请求
如有错误,欢迎指正!!!