Spring Boot 定制错误页面/错误数据
1. springboot 默认错误处理
浏览器访问,返回一个默认的错误页面
其他客户端访问,默认响应一个json数据
springboot中的错误处理自动配置:
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration@Configuration@ConditionalOnWebApplication(type=Type.SERVLET)@ConditionalOnClass({Servlet.class,DispatcherServlet.class})// Load before the main WebMvcAutoConfiguration so that the error View is available@AutoConfigureBefore(WebMvcAutoConfiguration.class)@EnableConfigurationProperties({ServerProperties.class,ResourceProperties.class,WebMvcProperties.class})publicclassErrorMvcAutoConfiguration{@Bean@ConditionalOnMissingBean(value=ErrorAttributes.class,search=SearchStrategy.CURRENT)publicDefaultErrorAttributeserrorAttributes(){returnnewDefaultErrorAttributes(this.serverProperties.getError().isIncludeException());}//处理错误请求,没有配置的时候默认处理/error请求@Bean@ConditionalOnMissingBean(value=ErrorController.class,search=SearchStrategy.CURRENT)publicBasicErrorControllerbasicErrorController(ErrorAttributes errorAttributes){returnnewBasicErrorController(errorAttributes,this.serverProperties.getError(),this.errorViewResolvers);}//系统出现错误以后来到error请求进行处理(web.xml注册错误页面)//注册错误页面响应规则@BeanpublicErrorPageCustomizererrorPageCustomizer(){returnnewErrorPageCustomizer(this.serverProperties,this.dispatcherServletPath);}@ConfigurationstaticclassDefaultErrorViewResolverConfiguration{privatefinalApplicationContext applicationContext;privatefinalResourceProperties resourceProperties;DefaultErrorViewResolverConfiguration(ApplicationContext applicationContext,ResourceProperties resourceProperties){this.applicationContext=applicationContext;this.resourceProperties=resourceProperties;}@Bean@ConditionalOnBean(DispatcherServlet.class)@ConditionalOnMissingBeanpublicDefaultErrorViewResolverconventionErrorViewResolver(){returnnewDefaultErrorViewResolver(this.applicationContext,this.resourceProperties);}}privatestaticclassErrorPageCustomizerimplementsErrorPageRegistrar,Ordered{privatefinalServerProperties properties;privatefinalDispatcherServletPath dispatcherServletPath;protectedErrorPageCustomizer(ServerProperties properties,DispatcherServletPath dispatcherServletPath){this.properties=properties;this.dispatcherServletPath=dispatcherServletPath;}//注册错误页面响应规则@OverridepublicvoidregisterErrorPages(ErrorPageRegistry errorPageRegistry){// /errorErrorPage errorPage=newErrorPage(this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));errorPageRegistry.addErrorPages(errorPage);}@OverridepublicintgetOrder(){return0;}}}//org.springframework.boot.autoconfigure.web.ErrorPropertiespublicclassErrorProperties{/** * Path of the error controller. */@Value("${error.path:/error}")privateString path="/error";...}//org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController@Controller@RequestMapping("${server.error.path:${error.path:/error}}")publicclassBasicErrorControllerextendsAbstractErrorController{...//产生html类型数据,处理浏览器请求@RequestMapping(produces=MediaType.TEXT_HTML_VALUE)publicModelAndViewerrorHtml(HttpServletRequest request,HttpServletResponse response){//状态码HttpStatus status=getStatus(request);//model数据//getErrorAttributes()调用DefaultErrorAttributes的getErrorAttributes()方法Map<String,Object>model=Collections.unmodifiableMap(getErrorAttributes(request,isIncludeStackTrace(request,MediaType.TEXT_HTML)));response.setStatus(status.value());//取哪个页面作为错误页面,包含页面地址和页面内容ModelAndView modelAndView=resolveErrorView(request,response,status,model);return(modelAndView!=null)?modelAndView:newModelAndView("error",model);}//产生json类型数据,处理其他客户端请求@RequestMappingpublicResponseEntity<Map<String,Object>>error(HttpServletRequest request){Map<String,Object>body=getErrorAttributes(request,isIncludeStackTrace(request,MediaType.ALL));HttpStatus status=getStatus(request);returnnewResponseEntity<>(body,status);}}//org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#resolveErrorView//所有的ErrorViewResolver 得到ModelAndViewprotectedModelAndViewresolveErrorView(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){returnmodelAndView;}}returnnull;}publicclassDefaultErrorViewResolverimplementsErrorViewResolver,Ordered{privatestaticfinalMap<Series,String>SERIES_VIEWS;static{Map<Series,String>views=newEnumMap<>(Series.class);views.put(Series.CLIENT_ERROR,"4xx");views.put(Series.SERVER_ERROR,"5xx");SERIES_VIEWS=Collections.unmodifiableMap(views);}...//@OverridepublicModelAndViewresolveErrorView(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);}returnmodelAndView;}privateModelAndViewresolve(String viewName,Map<String,Object>model){//默认找到一个页面 error/404String errorViewName="error/"+viewName;//如果模板引擎可以解析这个页面地址,就用模板引擎解析TemplateAvailabilityProvider provider=this.templateAvailabilityProviders.getProvider(errorViewName,this.applicationContext);if(provider!=null){//如果模板引擎可用,返回errorViewName指定的视图地址returnnewModelAndView(errorViewName,model);}returnresolveResource(errorViewName,model);}privateModelAndViewresolveResource(String viewName,Map<String,Object>model){//否则在静态资源文件夹下找errorViewName对应的html,error/404.htmlfor(String location:this.resourceProperties.getStaticLocations()){try{Resource resource=this.applicationContext.getResource(location);resource=resource.createRelative(viewName+".html");if(resource.exists()){returnnewModelAndView(newHtmlResourceView(resource),model);}}catch(Exceptionex){}}//没找到返回nullreturnnull;}}publicclassDefaultErrorAttributesimplementsErrorAttributes,HandlerExceptionResolver,Ordered{...//BasicErrorController#ModelAndView errorHtml()方法中调用的getErrorAttributes(),向错误处理的Model中添加数据publicMap<String,Object>getErrorAttributes(WebRequest webRequest,booleanincludeStackTrace){Map<String,Object>errorAttributes=newLinkedHashMap();errorAttributes.put("timestamp",newDate());//时间戳this.addStatus(errorAttributes,webRequest);//状态码this.addErrorDetails(errorAttributes,webRequest,includeStackTrace);this.addPath(errorAttributes,webRequest);returnerrorAttributes;}// "timestamp":时间戳// "status":状态码// "error":错误提示// "exception":异常对象// "message":异常信息// "errors": JSR303数据校验的错误// "trace":// "path":...}一旦系统出现4xx或者5xx等等错误,ErrorPageCustomer(定制错误的响应规则)就会生效,就会到/error请求,就会被BasicErrorController处理:
响应页面是由 **DefaultErrorViewResolver ** 解析得到的
如何定制错误处理页面:
有模板引擎情况下,error/状态码将错误页面命名为错误状态码.html,放在模板引擎文件夹里面的error文件夹下,发生此状态码的错误就会来到对应的页面error/404.html也可以用error4xx.html匹配所有4xx的错误状态码
在没有模板引擎的情况下(模板引擎找不到error页面),会在静态资源文件夹下找
以上都没有的时候错误页面,会到springboot默认错误提示页面
原理:
可以参照ErrorMvcAutoConfiguration 错误处理的自动配置
给容器中添加了以下组件:DefaultErrorAttributes:帮我们在页面控制信息
代码在上面
如何定制错误处理json数据:
Springmvc中可以使用@ControllerAdvice和@ExceptionHandler({MyException.class})来处理请求异常。这种方法不能自适应 返回页面和数据 的不同情况
要自适应可以转发到springboot的/error处理
@ExceptionHandler({MyException.class})publicStringhandleMyException(Exception e){Map<String,Object>map=newHashMap<String,Objcet>();map.put("code","user.notexist");map.put("message",e.getMessage());return"forward:/error";//}这种方法可以自适应,但还是来到了错误空白页面,错误视图没有解析到,因为返回的status状态码=200,要进入错误处理页面,我们需要传入自己的错误状态码org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getStatus()方法可以看到是request域中的一个属性"javax.servlet.error.status_code"
@ExceptionHandler({MyException.class})publicStringhandleMyException(Exception e, HttpServletRequest request){Map<String,Object>map=newHashMap<String,Objcet>();map.put("code","user.notexist");map.put("message",e.getMessage());request.setAttribute("ext",map);//用于在后面自定义返回数据中取出,返回给页面和jsonrequest.setAttribute("javax.servlet.error.status_code",400);return"forward:/error";//}如果要将我们的定制数据携带出去:
在出现错误后,会来到/error请求,会被BasicErrorController处理,响应出去可以获取的数据由org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#errorHtml()方法中的getErrorAttributes(),也就是org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes()方法得到。
因为
@Bean@ConditionalOnMissingBean(value=ErrorController.class,search=SearchStrategy.CURRENT)publicBasicErrorControllerbasicErrorController(ErrorAttributes errorAttributes){returnnewBasicErrorController(errorAttributes,this.serverProperties.getError(),this.errorViewResolvers);}第一种方法: 我们可以自定义一个ErrorController实现类,或者org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController的子类放在容器中。
而又因为org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController#getErrorAttributes()是在调用org.springframework.boot.web.servlet.error.DefaultErrorAttributes#getErrorAttributes()方法,
因为
@Bean@ConditionalOnMissingBean(value=ErrorAttributes.class,search=SearchStrategy.CURRENT)publicDefaultErrorAttributeserrorAttributes(){returnnewDefaultErrorAttributes(this.serverProperties.getError().isIncludeException());}所以我们可以自定义ErrorAttributes的实现类,或者继承DefaultErrorAttributes,添加自己定义的属性返回给页面
@ComponentpublicextendsDefaultErrorAttributes{@OverridepublicMap<String,Object>getErrorAttributes(WebRequest webRequest,booleanincludeStackTrace){Map<String,Object>errorAttributes=super.getErrorAttributes(webRequest,includeStackTrace);errorAttributes.put("name","wangteng");returnerrorAttributes;//页面和json能获取的所有字段}}如果要返回在异常处理中添加的信息,可以将数据先放在request中
@ComponentpublicextendsDefaultErrorAttributes{@OverridepublicMap<String,Object>getErrorAttributes(WebRequest webRequest,booleanincludeStackTrace){Map<String,Object>errorAttributes=super.getErrorAttributes(webRequest,includeStackTrace);errorAttributes.put("name","wangteng");Map<String,Object>ext=(Map<String,Object>)webRequest.getAttribute("ext",0);//异常处理器携带数据errorAttributes.put("ext",ext);returnerrorAttributes;//页面和json能获取的所有字段}}