SpringBoot
-
默认错误处理机制:
-
错误演示:
* 原理:
* 定制错误响应: -
定制错误页面响应:
* 定制错误json数据响应:
默认错误处理机制:
错误演示:
浏览器页面请求: 返回错误页面,请求头类型 text/html ;
其他客户端请求: 响应 json 数据;
原理:
参照ErrorMVCAutoConfiguration,错误处理的自动配置;
给容器添加以下组件:
DefaultErrorAttributes: 帮助在页面共享信息,DefaultErrorAttributes.getErrorAttributes() 是默认进行数据处理的;
1
2
3
4
5
6
7 1 @Bean
2 @ConditionalOnMissingBean(value = {ErrorAttributes.class},search = SearchStrategy.CURRENT)
3 public DefaultErrorAttributes errorAttributes() {
4 return new DefaultErrorAttributes(this.serverProperties.getError().isIncludeException());
5 }
6
7
1
2
3
4
5
6
7
8
9
10 1 public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
2 Map<String, Object> errorAttributes = new LinkedHashMap();
3 errorAttributes.put("timestamp", new Date());
4 this.addStatus(errorAttributes, webRequest);
5 this.addErrorDetails(errorAttributes, webRequest, includeStackTrace);
6 this.addPath(errorAttributes, webRequest);
7 return errorAttributes;
8 }
9
10
timestamp
时间戳
status
状态码
error
错误提示
exception
异常对象
message
异常消息
errors
JSR303数据校验的错误
BasicErrorController: 处理默认 /error 请求;
1
2
3
4
5
6
7 1 @Bean
2 @ConditionalOnMissingBean( value = {ErrorController.class},search = SearchStrategy.CURRENT)
3 public BasicErrorController basicErrorController(ErrorAttributes errorAttributes, ObjectProvider<ErrorViewResolver> errorViewResolvers) {
4 return new BasicErrorController(errorAttributes, this.serverProperties.getError(), (List)errorViewResolvers.orderedStream().collect(Collectors.toList()));
5 }
6
7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 1@Controller
2@RequestMapping({"${server.error.path:${error.path:/error}}"})
3public class BasicErrorController extends AbstractErrorController {
4
5 ......
6
7 @RequestMapping(produces = {"text/html"}) //产生html数据,浏览器发送的请求采用这个方法处理
8 public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
9 HttpStatus status = this.getStatus(request);
10 Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
11 response.setStatus(status.value());
12
13 //找寻页面作为错误页面;包含页面地址和页面内容
14 ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
15 return modelAndView != null ? modelAndView : new ModelAndView("error", model);
16 }
17
18 @RequestMapping //产生json数据,其他客户端采用这个方法处理
19 public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
20 HttpStatus status = this.getStatus(request);
21 if (status == HttpStatus.NO_CONTENT) {
22 return new ResponseEntity(status);
23 } else {
24 Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
25 return new ResponseEntity(body, status);
26 }
27 }
28}
29
30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 1 protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
2 Iterator var5 = this.errorViewResolvers.iterator();
3
4 ModelAndView modelAndView;
5 //采用 do while 循环,所有的ErrorViewResolver得到ModelAndView
6 do {
7 if (!var5.hasNext()) {
8 return null;
9 }
10
11 ErrorViewResolver resolver = (ErrorViewResolver)var5.next();
12 modelAndView = resolver.resolveErrorView(request, status, model);
13 } while(modelAndView == null);
14
15 return modelAndView;
16 }
17
18
ErrorPageCustomizer: 当系统出现4xx或者5xx之类的错误,ErrorPageCustomizer 生效,进行错误响应规则的定制;
1
2
3
4
5
6 1 @Bean
2 public ErrorMvcAutoConfiguration.ErrorPageCustomizer errorPageCustomizer(DispatcherServletPath dispatcherServletPath) {
3 return new ErrorMvcAutoConfiguration.ErrorPageCustomizer(this.serverProperties, dispatcherServletPath);
4 }
5
6
1
2
3
4
5
6
7
8
9
10
11 1private static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered {
2 ...
3 public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
4
5 ErrorPage errorPage = new ErrorPage(this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
6 errorPageRegistry.addErrorPages(new ErrorPage[]{errorPage});
7 }
8 ...
9 }
10
11
1
2
3
4
5
6
7
8
9
10
11 1public class ErrorProperties {
2 @Value("${error.path:/error}")
3 private String path = "/error"; //系统出现错误以后,来到error请求进行处理
4
5 public String getPath() {
6 return this.path;
7 }
8 ...
9}
10
11
DefaultErrorViewResolver: 由DefaultErrorViewResolver进行解析,得到错误响应页面;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 1 @Configuration(proxyBeanMethods = false)
2 static class DefaultErrorViewResolverConfiguration {
3 ...
4
5 DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext, ResourceProperties resourceProperties) {
6 this.applicationContext = applicationContext;
7 this.resourceProperties = resourceProperties;
8 }
9
10 @Bean
11 @ConditionalOnBean({DispatcherServlet.class})
12 @ConditionalOnMissingBean({ErrorViewResolver.class})
13 DefaultErrorViewResolver conventionErrorViewResolver() {
14 return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties);
15 }
16 }
17
18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43 1 public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
2 ModelAndView modelAndView = this.resolve(String.valueOf(status.value()), model);
3 if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) {
4 modelAndView = this.resolve((String)SERIES_VIEWS.get(status.series()), model);
5 }
6
7 return modelAndView;
8 }
9
10 private ModelAndView resolve(String viewName, Map<String, Object> model) {
11 //默认SpringBoot可以去找到一个页面, error/404
12 String errorViewName = "error/" + viewName;
13 //模板引擎可以解析这个页面地址就用模板引擎解析
14 TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext);
15 /**
16 * 模板引擎可用的情况下返回到errorViewName指定的视图地址
17 * 模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html
18 */
19 return provider != null ? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName, model);
20 }
21
22 private ModelAndView resolveResource(String viewName, Map<String, Object> model) {
23 String[] var3 = this.resourceProperties.getStaticLocations();
24 int var4 = var3.length;
25
26 for(int var5 = 0; var5 < var4; ++var5) {
27 String location = var3[var5];
28
29 try {
30 Resource resource = this.applicationContext.getResource(location);
31 resource = resource.createRelative(viewName + ".html");
32 if (resource.exists()) {
33 return new ModelAndView(new DefaultErrorViewResolver.HtmlResourceView(resource), model);
34 }
35 } catch (Exception var8) {
36 ;
37 }
38 }
39
40 return null;
41 }
42
43
定制错误响应:
定制错误页面响应:
模板引擎文件夹下有: 将错误页面命名为错误状态码.html ,放在模板引擎文件夹下的error文件夹里面,发生此状态码的错误就会来到对应的页面;我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,优先寻找精确的状态码.html;
模板引擎文件夹下没有,静态资源文件夹下有: 放在静态资源文件夹下的error文件夹里面;
模板引擎文件夹下没有,静态资源文件夹下没有: 默认来到SpringBoot默认的错误提示页面;
示例:
注意点:获取不到异常类型的情况,在配置文件中添加 server.error.include-exception=true
定制错误json数据响应:
自定义异常处理&返回定制json数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 1
2@ControllerAdvice //使用 ControllerAdvice注解 定义成为异常处理器组件
3public class MyExceptionHandler {
4
5 @ResponseBody
6 @ExceptionHandler(UserNotExistException.class)
7 public Map<String,Object> handleException(Exception e){
8 Map<String,Object> map = new HashMap<>();
9 map.put("code","user.notexist");
10 map.put("message",e.getMessage());
11 return map;
12 }
13}
14注意点:这种写法,浏览器客户端返回的都是json
15
16
转发到/error进行自适应响应效果处理:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 1@ControllerAdvice //使用 ControllerAdvice注解 定义成为异常处理器组件
2public class MyExceptionHandler {
3
4 @ExceptionHandler(UserNotExistException.class)
5 public String handleException(Exception e, HttpServletRequest request){
6 Map<String,Object> map = new HashMap<>();
7 //传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程
8 // Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
9 request.setAttribute("javax.servlet.error.status_code",500);
10 map.put("code","user.notexist");
11 map.put("message","用户出错啦");
12
13 request.setAttribute("ext",map);
14 //转发到/error
15 return "forward:/error";
16 }
17}
18注意点:此时在客户端,仍然不会显示 code:user.notexist 和 message:用户出错啦 ;
19
20
定制json数据携带展示:
可以通过自定义ErrorAttributes改变需要返回的内容,实现自适应的响应;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 1//给容器中加入我们自己定义的ErrorAttributes,而不使用默认配置
2@Component
3public class MyErrorAttributes extends DefaultErrorAttributes {
4
5 //返回值的map就是页面和json能获取的所有字段
6 @Override
7 public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
8 Map<String, Object> map = super.getErrorAttributes(webRequest, includeStackTrace);
9 map.put("company","yp");
10
11 //自己的异常处理器携带的数据
12 Map<String,Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", 0); // 0 代表从REQUEST域 获取, 1 代表从 SESSION域 获取
13 map.put("ext",ext);
14 return map;
15 }
16}
17
18 //定义构造器,否则浏览器页面不能正常获取 exception
19 public MyErrorAttributes() {
20 super(true);
21 }
22
23
最终效果图: