1. first , Previous structure

2. next , It's the text
1),SpringBoot Default error handling mechanism

Default effect :
1), browser , Return to a default error page
Request header for browser to send request :
2), If it's another client , Default response one json data
principle :
Can refer to ErrorMvcAutoConfiguration; Automatic configuration of error handling ; The following components were added to the container 1,DefaultErrorAttributes:
Help us share information on the page ; @Override public Map<String, Object>
getErrorAttributes(RequestAttributes requestAttributes, boolean
includeStackTrace) { Map<String, Object> errorAttributes = new
LinkedHashMap<String, Object>(); errorAttributes.put("timestamp", new Date());
addStatus(errorAttributes, requestAttributes); addErrorDetails(errorAttributes,
requestAttributes, includeStackTrace); addPath(errorAttributes,
requestAttributes); return errorAttributes; }
2,BasicErrorController: Handle default /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 = getStatus(request); Map<String, Object> model =
Collections.unmodifiableMap(getErrorAttributes( request,
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 = resolveErrorView(request, response, status, model); return
(modelAndView == null ? new ModelAndView("error", model) : modelAndView); }
@RequestMapping @ResponseBody // produce json data , Other clients come to this method to process ; public
ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status =
getStatus(request); return new ResponseEntity<Map<String, Object>>(body,
status); } 3,ErrorPageCustomizer: @Value("${error.path:/error}") private String
path = "/error"; After system error error Request for processing ;(web.xml Registered error page rules )
4,DefaultErrorViewResolver: @Override public ModelAndView
resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String,
Object> model) { ModelAndView modelAndView = resolve(String.valueOf(status),
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) { // default SpringBoot You can find a page ? error/404 String errorViewName =
"error/" + viewName; // The template engine can resolve this page address, and then it can use the template engine to resolve it TemplateAvailabilityProvider
provider = this.templateAvailabilityProviders .getProvider(errorViewName,
this.applicationContext); if (provider != null) {
// Return to when the template engine is available errorViewName Specified view address return new ModelAndView(errorViewName,
model); } // Template engine not available , Under the static resource folder errorViewName Corresponding page error/404.html return
resolveResource(errorViewName, model); } step :
Once the system appears 4xx perhaps 5xx Mistakes like that ;ErrorPageCustomizer It will take effect ( Custom error response rules ); Will come /error request ; Will be BasicErrorController handle ;
1) 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 for (ErrorViewResolver resolver :
this.errorViewResolvers) { ModelAndView modelAndView =
resolver.resolveErrorView(request, status, model); if (modelAndView != null) {
return modelAndView; } } return null; }
2), If custom error response :

1), How to customize the wrong page ;
1), With template engine ;error/ Status code ; 【 Name the error page Error status code .html In the template engine folder
error Under folder 】, An error with this status code will occur Corresponding page ;
We can use 4xx and 5xx Match all errors of this type as the filename of the error page , Precision first ( Priority to find 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 2), No template engine ( The template engine could not find this error page ), Static resource folder ;
3), There are no error pages above , It's the default SpringBoot Default error prompt page ;
2), How to customize the wrong json data ;
1), Custom exception handling & Back to customization json data ; @ControllerAdvice public class MyExceptionHandler {
@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 ...
2), 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",e.getMessage()); // Forward to /error
return "forward:/error"; }
3), Take our customized data out ;

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 { @Override public Map<String, Object>
getErrorAttributes(RequestAttributes requestAttributes, boolean
includeStackTrace) { Map<String, Object> map =
super.getErrorAttributes(requestAttributes, includeStackTrace);
map.put("company","atguigu"); return map; } }
Final effect : The response is adaptive , Can be customized ErrorAttributes Change what needs to be returned ,

©2019-2020 Toolsou All rights reserved,
TP6 Application examples of verifier and correct verification data Unity Scene loading asynchronously ( Implementation of loading interface ) Gude Haowen serial - You deserve to be an engineer ( Preface ) Bitcoin in ten years ,VDS Opportunity or fraud Huawei certification HCIA-AI artificial intelligence Image explanation of over fitting and under fitting Python Basic knowledge and notes ESP8266/ESP32 System : Optimize system startup time First knowledge python Skills summary use C++ I want to talk to you “ Prototype mode ” ( copy / copy constructor )