1, the default error handling mechanism
Springboot when a page request error occurs, a default page is returned, such as:
Browser as Client
If you are using a browser as the client to access the interface, then in the browser's request header there will be
accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*; q=0.8
Other clients
Accept: * /*
The default response is a JSON data
{"timestamp": 1538381770900,"status": 404,"error": "Not Found","message": "No" Message available "," path ":"/crud/aaa "}
2. Automatic configuration of error handling
Automatic configuration class for error handling: errormvcautoconfiguration
Add the following components to the container
Share information in a page
PublicMap<string, object> geterrorattributes (Requestattributes requestattributes,Booleanincludestacktrace) {Map<string, object> errorattributes =NewLinkedhashmap (); Errorattributes.put ("Timestamp",NewDate ()); This. Addstatus (Errorattributes, requestattributes); This. Adderrordetails (Errorattributes, Requestattributes, includestacktrace); This. Addpath (Errorattributes, requestattributes); returnerrorattributes;}
Handles the default/error request, which, if the client is a Web browser, is processed in the following way, producing the HTML type of data.
@RequestMapping (produces= {"Text/html"}) PublicModelandview 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 ()); Modelandview Modelandview= This. Resolveerrorview (Request, response, status, model); returnModelandview! =NULL? Modelandview:NewModelandview ("Error", model);}
If it is another client, use the following method to process the return JSON data
@RequestMapping @responsebody Public responseentity<map<string, object>> error (HttpServletRequest request) { Mapthis This . Isincludestacktrace (Request, Mediatype.all)); This . GetStatus (request); return New responseentity (body, status);}
The system error is later processed to the error request.
@Value ("${error.path:/error}")private String path = "/error";
PublicModelandview 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); } returnModelandview;}PrivateModelandview Resolve (String viewName, map<string, object>model) { //default springboot will go to find a page/error/404String errorviewname = "error/" +ViewName; //if the template engine can parse this page address, use this template engine to parseTemplateavailabilityprovider Provider = This. Templateavailabilityproviders.getprovider (Errorviewname, This. ApplicationContext); //the template engine resolves and returns the address specified by Errorviewname//template engine can not be used to go to the static resources folder below to find/error/404.html page returnProvider! =NULL?NewModelandview (Errorviewname, model): This. ResolveResource (errorviewname, model);}
3. Configuration steps
Once the system appears 4xx or 5xx error, Errorpagecustomizer will take effect (custom error response rule); will come to/error request; it will be basicerrorcontroller. To which page is parsed by defaulterrorviewresolver
Custom error page
1), there is a template engine case: error/status code; "Name the error page as an error status code." HTML in the template engine folder inside the error folder ", the occurrence of this status code error will come to the corresponding page;
We can use 4xx and 5xx as the file name of the error page to match all errors of this type, with precision precedence (first looking for an exact status code. html);
The information that the page can get
- Timestamp: Time stamp
- Status: State code
- Error: Wrong prompt
- Exception: Exception object
- Message: Exception messages
- errors:jsr303 data checksum errors are here.
In the case of a template engine, you can use the following notation to get information
class= "col-md-9 ml-sm-auto col-lg-10 pt-3 px-4" >
2), no template engine (template engine can not find this error page), static resource folder to find;
3), the above are not error page, is the default to springboot default error prompt page;
Custom error JSON data to customize an exception Public class extends runtimeexception { public usernotexistexception () { super("user does not exist" ); }}
Controller in@ResponseBody @requestmapping ("/hello") Public string Hello (@RequestParam ("User") string user) { if(user.equals ("AAA")) { ThrowNew usernotexistexception (); } return "HelloWorld";}
PageEffect{"timestamp": 1538453996437,"status": $,"error": "Internal Server Error"," Exception ":" Cn.zhuangxp.springboot.exception.UserNotExistException "," message ":" User does not exist "," path " : "/crud/hello"}
The JSON data returned above is Springboot help us to define, we can also define our own exception JSON information.
@ControllerAdvice Public class Myexceptionhandler { @ResponseBody @ExceptionHandler (usernotexistexception. class ) public map<string, object> handleexception (Exception e) { Map New hashmap<>(); Map.put ("code", "User.notexist"); Map.put ("msg", E.getmessage ()); return map; }}
Effect
{"msg": "User does not exist","code": "User.notexist"}
The above exception handling has no adaptive effect. The adaptive effect requires that if the page is returned by browser access, the JSON data is returned if other client access is available.
How to become an adaptive effect?
/*** Adaptive effects available *@paramE *@return */@ExceptionHandler (usernotexistexception.class) PublicString handleexception (Exception E, httpservletrequest request) {Map<String,Object> map =NewHashmap<>(); Request.setattribute ("Javax.servlet.error.status_code", 500); Map.put ("Code", "User.notexist"); Map.put ("Message", "User error"); //Place the above error message map in the request domainRequest.setattribute ("ext", map); return"Forward:/error";}
Write a custom error attribute class and add it to the container
@Component Public classMyerrorattributesextendsdefaulterrorattributes {@Override PublicMap<string, object> geterrorattributes (Requestattributes requestattributes,Booleanincludestacktrace) {Map<string, object> map =Super. Geterrorattributes (Requestattributes, includestacktrace); Map<String,Object> ext = (map<string, object>) requestattributes.getattribute ("ext", 0); //data carried by the exception processorMap.put ("name", "Zxp"); Map.put ("Ext", ext); returnmap; }}
Once this is written, the error will be redirected to the page we set up when accessing the browser. The corresponding JSON error message is returned with the other browser.
{"timestamp": 1538466112389,"status": $,"error": "Internal Server Error"," Exception ":" Cn.zhuangxp.springboot.exception.UserNotExistException "," message ":" User does not exist "," path " : "/crud/hello","name": "Zxp","ext":{ "code": "User.notexist", " Message ":" User Error " }}
V. Error handling mechanism