本文讨论Springboot2是如何处理页面访问错误的问题
在springboot中ErrorMvcAutoConfiguration类用来处理错误,它给容器中添加了好多组件
系统出现错误以后来到ErrorPageCustomizer,会默认发送error请求进行处理
static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered { protected ErrorPageCustomizer(ServerProperties properties, DispatcherServletPath dispatcherServletPath) { this.properties = properties; this.dispatcherServletPath = dispatcherServletPath; } @Override public void registerErrorPages(ErrorPageRegistry errorPageRegistry) { ErrorPage errorPage = new ErrorPage( this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath())); //@Value("${error.path:/error}") //private String path = "/error"; errorPageRegistry.addErrorPages(errorPage); }用来处理/error错误请求
@Controller @RequestMapping("${server.error.path:${error.path:/error}}") public class BasicErrorController extends AbstractErrorController { //产生html类型的数据;浏览器发送的请求来到这个方法处理 @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); Map<String, Object> model = Collections .unmodifiableMap(getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); //去哪个页面作为错误页面;包含页面地址和页面内容 ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView != null) ? modelAndView : new ModelAndView("error", model); } //产生json数据,其他客户端来到这个方法处理; @RequestMapping public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { HttpStatus status = getStatus(request); if (status == HttpStatus.NO_CONTENT) { return new ResponseEntity<>(status); } Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL)); return new ResponseEntity<>(body, status); } }在处理网页页面的过程中有个resolveErrorView方法,所有的ErrorViewResolver得到ModelAndView
protected ModelAndView resolveErrorView(HttpServletRequest request, HttpServletResponse response, HttpStatus status, Map<String, Object> model) { for (ErrorViewResolver resolver : this.errorViewResolvers) { ModelAndView modelAndView = resolver.resolveErrorView(request, status, model); if (modelAndView != null) { return modelAndView; } } return null; } }如果找不到就会返回null,BasicErrorController返回得到ModelAndView(“error”, model); 在ErrorMvcAutoConfiguration中,会自动生成一个页面
@Configuration(proxyBeanMethods = false) @ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true) @Conditional(ErrorTemplateMissingCondition.class) protected static class WhitelabelErrorViewConfiguration { private final StaticView defaultErrorView = new StaticView(); @Bean(name = "error") @ConditionalOnMissingBean(name = "error") public View defaultErrorView() { return this.defaultErrorView; //private final StaticView defaultErrorView = new StaticView(); // private static class StaticView implements View { }DefaultErrorViewResolver用来解析BasicErrorController返回的modelAndView的视图名
public class DefaultErrorViewResolver implements ErrorViewResolver, Ordered { static { Map<Series, String> views = new EnumMap<>(Series.class); views.put(Series.CLIENT_ERROR, "4xx"); views.put(Series.SERVER_ERROR, "5xx"); SERIES_VIEWS = Collections.unmodifiableMap(views); } @Override public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) { ModelAndView modelAndView = resolve(String.valueOf(status.value()), model); if (modelAndView == null && SERIES_VIEWS.containsKey(status.series())) { modelAndView = resolve(SERIES_VIEWS.get(status.series()), model); } return modelAndView; } private ModelAndView resolve(String viewName, Map<String, Object> model) { //默认SpringBoot可以去找到一个页面? error/404 String errorViewName = "error/" + viewName; //模板引擎可以解析这个页面地址就用模板引擎解析 TemplateAvailabilityProvider provider = this.templateAvailabilityProviders.getProvider(errorViewName, this.applicationContext); if (provider != null) { //模板引擎可用的情况下返回到errorViewName指定的视图地址 return new ModelAndView(errorViewName, model); } //模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 error/404.html return resolveResource(errorViewName, model); } //模板引擎不可用,就在静态资源文件夹下找errorViewName对应的页面 private ModelAndView resolveResource(String viewName, Map<String, Object> model) { for (String location : this.resourceProperties.getStaticLocations()) { try { Resource resource = this.applicationContext.getResource(location); resource = resource.createRelative(viewName + ".html"); if (resource.exists()) { return new ModelAndView(new HtmlResourceView(resource), model); } } catch (Exception ex) { } } return null; }在BasicErrorController中有个getErrorAttributes方法给页面model放置数据,这个方法是ErrorAttributes类来调用的,DefaultErrorAttributes是ErrorAttributes的实现,所以它才是默认进行数据处理
public abstract class AbstractErrorController implements ErrorController { private final ErrorAttributes errorAttributes; protected Map<String, Object> getErrorAttributes(HttpServletRequest request, ErrorAttributeOptions options) { WebRequest webRequest = new ServletWebRequest(request); return this.errorAttributes.getErrorAttributes(webRequest, options); } ----------------------------------------------------------------------- public class DefaultErrorAttributes implements ErrorAttributes, HandlerExceptionResolver, Ordered { @Override @Deprecated public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) { Map<String, Object> errorAttributes = new LinkedHashMap<>(); errorAttributes.put("timestamp", new Date()); addStatus(errorAttributes, webRequest); addErrorDetails(errorAttributes, webRequest, includeStackTrace); addPath(errorAttributes, webRequest); return errorAttributes; }页面能获取的信息; timestamp:时间戳 status:状态码 error:错误提示 exception:异常对象 message:异常消息 errors:JSR303数据校验的错误都在这里
根据默认错误处理原理可知,一但系统出现4xx或者5xx之类的错误;ErrorPageCustomizer就会生效(定制错误的响应规则);就会来到/error 请求;就会被BasicErrorController处理;DefaultErrorViewResolver会解析视图名,DefaultErrorAttributes用来传递错误信息,响应出去可以获取的数据是由 getErrorAttributes得到的(是AbstractErrorController(ErrorController)规定的方法);
如果我们不想用springboot的默认错误响应页面,我们可以自定义错误响应页面,根据原理:
将错误页面命名为 错误状态码.html 放在模板引擎文件夹里面的 error文件夹下,发生此状态码的错误就会来到 对应的页面; 我们可以使用4xx和5xx作为错误页面的文件名来匹配这种类型的所有错误,精确优先(优先寻找精确的状态 码.html); 在这种情况下,我们还能获得以下错误信息
timestamp:时间戳 status:状态码 error:错误提示 exception:异常对象 message:异常消息 errors:JSR303数据校验的错误都在这里
例如,把一个命名为4xx.html(或者404.html)的页面放到模板文件夹的error文件夹下 页面代码如下:
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4"> <h1>4xx</h1> <h1>status:[[${status}]]</h1> <h1>timestamp:[[${timestamp}]]</h1> </main>发生一个错误,显示页面如下
我们现在使用的都是默认的异常处理类,如果我们从客户端访问项目,如何获得自定义的json数据??这就需要我们自定义异常处理类,在这个类中设置自定义数据
定义一个controller,用来测试
@Controller public class Helloworld { @ResponseBody @RequestMapping("/hello") public String hello(@RequestParam("user")String user){ if(user.equals("aaa")){ throw new UserNotExistException(); } return "hello world!"; }设置
server.error.include-exception=true server.error.include-message=always
如果发生了这个异常,会使用默认的异常处理类处理
从浏览器触发异常,测试结果,我们获得了自定义json数据,而不是自适应处理 但是这种处理方式只能获得json数据
利用BasicErrorController进行自适应处理,但需要手动传入状态码,否则就不会进入定制错误页面的解析流程
@ControllerAdvice public class MyExceptionHandler { @ExceptionHandler(UserNotExistException.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.notexist"); map.put("message",e.getMessage()); //转发到/error让BasicErrorController处理 return "forward:/error"; } }测试结果,确实获得了自适应效果,但是我们自定义的数据没有传递出来
根据原理,数据是通过getErrorAttributes得到的是(AbstractErrorController(ErrorController)规定的方法),而在AbstractErrorController类中getErrorAttributes方法是ErrorAttributes类来调用的,DefaultErrorAttributes是ErrorAttributes的实现,所以我们可以: 1.完全来编写一个ErrorController的实现类【或者是编写AbstractErrorController的子类】,放在容器中,取代BasicErrorController; 2.自定义一个ErrorAttributes取代DefaultErrorAttributes,重写getErrorAttributes方法,那么BasicErrorController就会调用我们这个方法 试验第二种方法,自定义一个ErrorAttributes继承DefaultErrorAttributes
package com.sxt.springboot.component; import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; @Component public class MyErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { //调父类的方法,会把原方法执行完,再到本方法 Map<String,Object> errorAttributes =super.getErrorAttributes(webRequest, options); //传递数据 errorAttributes.put("company","sxt"); return errorAttributes; } }测试结果,数据传递过来了 那么我们怎么把自定义异常处理类里面的数据传递出来? 首先在自定义异常处理类把数据放request
@ControllerAdvice public class MyExceptionHandler { @ExceptionHandler(UserNotExistException.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.notexist"); map.put("message","用户出错了"); //把扩展数据放入请求域中传递 request.setAttribute("ext",map); //转发到/error让BasicErrorController处理 return "forward:/error"; } }然后在自定义ErrorAttributes取出放入返回值里面
package com.sxt.springboot.component; import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; @Component public class MyErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { //调父类的方法,会把原方法执行完,再到本方法 Map<String,Object> errorAttributes =super.getErrorAttributes(webRequest, options); //传递数据 errorAttributes.put("company","sxt"); //获取请求域的数据 Map<String,Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", 0); //把数据加进来 errorAttributes.put("ext",ext); return errorAttributes; } }测试结果,既获得数据又得到自适应
Springboot2错误处理机制,需要理解各个组件的作用,以及如何自定义组件