principle :

          Can refer to ErrorMvcAutoConfiguration : Automatic configuration of error handling

          Add the following components to the container :

          1,DefaultErrorAttributes: Share information on page

          2,BasicErrorController: Handle default /error request

          3,ErrorPageCustomizer: Custom error response rules

          4,DefaultErrorViewResolver : View page for response resolution

step :

          1, Once the system appears 4xx perhaps 5xx Mistakes like that ,ErrorPageCustomizer It will take effect , Will come /error request ;
@Value("${error.path:/error}") private String path =
"/error";// After system error error Request for processing ;( similar web.xml Registered error page rules )
          2, Will be BasicErrorController handle /error request
@Controller @RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController { .....
@RequestMapping(produces = {"text/html"}) // produce html Data of type , Requests sent by browsers come to this method for processing public
ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse
response) { HttpStatus status = this.getStatus(request); Map<String, Object>
model = Collections.unmodifiableMap(this.getErrorAttributes(request,
this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value()); // Which page to go to as the error page , Include page address and content ModelAndView
modelAndView = this.resolveErrorView(request, response, status, model); return
modelAndView == null ? new ModelAndView("error", model) : modelAndView; }
@RequestMapping @ResponseBody // produce json Data of type , Other clients come to this method to process public
ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = this.getErrorAttributes(request,
this.isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status =
this.getStatus(request); return new ResponseEntity(body, status); } .....
// Request header of browser request accept: first "text/html", So browser access will get a html Blank of ( Error message page ) page
// Request headers for other clients to send requests accept:"*/*", So client access will get a string json Data in format }
          3, Response page : Which page to go by  DefaultErrorViewResolver Analytic result
protected ModelAndView resolveErrorView(HttpServletRequest request,
HttpServletResponse response, HttpStatus status, Map<String, Object> model) {
// be-all ErrorViewResolver obtain ModelAndView Iterator var5 =
this.errorViewResolvers.iterator(); ModelAndView modelAndView; do { if
(!var5.hasNext()) { return null; } ErrorViewResolver resolver =
(ErrorViewResolver); modelAndView =
resolver.resolveErrorView(request, status, model); } while(modelAndView ==
null); return modelAndView; }
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus
status, Map<String, Object> model) { ModelAndView modelAndView =
this.resolve(String.valueOf(status), model); 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) { // default Spring Boot You can find a page error/404.html String errorViewName =
"error/" + viewName; // The template engine can parse the page address and use the template engine TemplateAvailabilityProvider
provider = this.templateAvailabilityProviders.getProvider(errorViewName,
this.applicationContext); // When the template engine is available , return errorViewName Specified view address
// Template engine not available , Under the static resource folder errorViewName Corresponding page error/404.html return provider != null
? new ModelAndView(errorViewName, model) : this.resolveResource(errorViewName,
model); }
4.DefaultErrorAttributes Share information on page
public Map<String, Object> getErrorAttributes(RequestAttributes
requestAttributes, boolean includeStackTrace) { Map<String, Object>
errorAttributes = new LinkedHashMap(); errorAttributes.put("timestamp", new
Date()); this.addStatus(errorAttributes, requestAttributes);
this.addErrorDetails(errorAttributes, requestAttributes, includeStackTrace);
this.addPath(errorAttributes, requestAttributes); return errorAttributes; }
How to customize error response :

     1, How to customize the wrong page

          ①: With template engine :/error/ Status code    【 Name the error page   Error status code .html In the template engine folder
error Under folder 】, If an error occurs in this status code, the corresponding page will appear ; have access to 4xx and 5xx Match all errors of this type as the filename of the error page , Precision first ( Priority for accurate
Status code .html);
Information available on the page ; ​ timestamp: time stamp ​ status: Status code ​ error: Error prompt ​ exception: Exception object ​
message: Exception message ​ errors:JSR303 Here are all the errors in data verification <h1>status:[[${status}]]</h1>
<h2>timestamp:[[${timestamp}]]</h2> .....
          ②: No template engine ( The template engine could not find this error page ), Static resource folder ;

          ③: There are no error pages above , It's the default SpringBoot Default error prompt page ;

     2, How to customize the wrong json data

          ①: Custom handling exception & Back to customization json data ;
//1, The browser client returns all json @ResponseBody
@ExceptionHandler(UserNotExistException.class) public Map<String,Object>
handleException(Exception e){ Map<String,Object> map = new HashMap<>();
map.put("code","user.notexist"); map.put("message",e.getMessage()); return map;
} // No adaptive effect .
          ②: Forward to /error Conduct adaptive response effect processing
@ExceptionHandler(UserNotExistException.class) public String
handleException(Exception e, HttpServletRequest request){ Map<String,Object>
map = new HashMap<>(); // Pass in our own error status code 4xx 5xx, Otherwise, you will not enter the resolution process of the customized error page /** * Integer
statusCode = (Integer) request
.getAttribute("javax.servlet.error.status_code"); */
map.put("code","user.notexist"); map.put("message"," User error ");
request.setAttribute("ext",map); // Forward to /error return "forward:/error"; }
          ③: Carry out customized data :

  After an error , Will come /error request , Will be BasicErrorController handle , The data that can be obtained after responding is getErrorAttributes Got it  
       ( yes AbstractErrorController(ErrorController) Prescribed method );

​    1, To write a ErrorController Implementation class of 【 Or writing AbstractErrorController Subclass of 】, Put in container ;

​    2, Data available on the page , Or maybe json All available data is returned through errorAttributes.getErrorAttributes obtain ;

​             In container DefaultErrorAttributes.getErrorAttributes(); Default for data processing ;

custom ErrorAttributes
// Add our own definition to the container ErrorAttributes @Component public class MyErrorAttributes
extends DefaultErrorAttributes { // Of the return value map Page and json All fields available @Override public
Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
boolean includeStackTrace) { Map<String, Object> map =
super.getErrorAttributes(requestAttributes, includeStackTrace);
map.put("company","atguigu"); // Data carried by our exception handler Map<String,Object> ext =
(Map<String, Object>) requestAttributes.getAttribute("ext", 0);
map.put("ext",ext); return map; } }
Final effect : The response is adaptive , Can be customized ErrorAttributes Change what needs to be returned
<h1>status:[[${status}]]</h1> <h2>timestamp:[[${timestamp}]]</h2>
<h2>exception:[[${exception}]]</h2> <h2>message:[[${message}]]</h2>
<h2>ext:[[${ext.code}]]</h2> <h2>ext:[[${ext.message}]]</h2>
This article needs to be browsed in combination with the text notes in the code snippet .





©2019-2020 Toolsou All rights reserved,
Python Basic knowledge and notes Programmer Tanabata Valentine's Day confession code NOI2019 travels China's longest high speed rail officially opened ! The fastest way to finish the race 30.5 hour C Language programming to find a student's grade Software testing BUG describe ESP8266/ESP32 System : Optimize system startup time Unity Scene loading asynchronously ( Implementation of loading interface ) Baidu , Ali , Tencent's internal position level and salary structure , With job suggestions !PYTHON Summary of final review