Spring Boot exception handling (GO)

Source: Internet
Author: User

Spring boot in exception handling, a Embeddedservletcontainercustomizer is implemented by default and an error page is defined to "/error". You can see it in the Errormvcautoconfiguration source code.

/**
* {@link Embeddedservletcontainercustomizer} that configures the container ' s error
* pages.
*/
Private Static class Errorpagecustomizer
Implements Embeddedservletcontainercustomizer, Ordered {

Private FinalServerproperties properties;

protected Errorpagecustomizer(Serverproperties properties) {
This. Properties = Properties;
}

@Override
Public void Customize(Configurableembeddedservletcontainer Container) {
Container.adderrorpages (NewErrorPage ( This. Properties.getservletprefix ()
+ This. Properties.geterror (). GetPath ()));
}

@Override
Public int GetOrder() {
return 0;
}

}

Also configured a default Whiteboard page, in the source can see

@Configuration
@ConditionalOnProperty(prefix ="Server.error.whitelabel", name ="Enabled", matchifmissing =true)
@Conditional(Errortemplatemissingcondition.class)
protected Static class whitelabelerrorviewconfiguration {

Private FinalSpelview Defaulterrorview =NewSpelview (
"
+"<p>this application have no explicit mapping for/error, so is seeing this as a fallback.</p>"
+"<div id= ' created ' >${timestamp}</div>"
+"<div>there is an unexpected error (Type=${error}, status=${status}) .</div>"
+"<div>${message}</div></body>);

@Bean(name ="Error")
@ConditionalOnMissingBean(name ="Error")
PublicViewDefaulterrorview() {
return This. Defaulterrorview;
}

//If The user adds @EnableWebMvc then the Bean name View Resolver from
//Webmvcautoconfiguration disappears, so add it back in to avoid disappointment.
@Bean
@ConditionalOnMissingBean(Beannameviewresolver.class)
PublicBeannameviewresolverBeannameviewresolver() {
Beannameviewresolver resolver =NewBeannameviewresolver ();
Resolver.setorder (Ordered.lowest_precedence-Ten);
returnResolver
}

}

On the processing of the path, a basicerrorcontroller is defined to handle the exception, errorattributes to load the error exception to the front

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
Public class basicerrorcontroller extends abstracterrorcontroller {

Private FinalErrorproperties errorproperties;

//...

@RequestMapping(produces ="Text/html")
PublicModelandviewerrorHtml(HttpServletRequest request,
HttpServletResponse response) {
Response.setstatus (GetStatus (Request). value ());
map<string, object> model = geterrorattributes (Request,
Isincludestacktrace (Request, mediatype.text_html));
return NewModelandview ("Error", model);
}

@RequestMapping
@ResponseBody
PublicResponseentity<map<string, object>>Error(HttpServletRequest request) {
map<string, object> BODY = geterrorattributes (Request,
Isincludestacktrace (Request, Mediatype.all));
Httpstatus status = GetStatus (request);
return NewResponseentity<map<string, object>> (body, status);
}

//...}

Default as long as you request the Content-type is "text/html" then return a white version page to you, if it is the other content-type, then return a JSON data to you.

If you want to customize the exception, you can handle it in the following ways

1. You can define an exception page by default under Classpath:templates to define a ERROR.FTL freemarker template

<! DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert Title here</title>
</head>
<body>

<H1>Error page!!</H1>

${timestamp?string (' Yyyy-mm-dd HH:mm:ss ')}<br/><br/>
${status}<br/><br/>
${error}<br/><br/>
${message}<br/><br/>
${path}<br/><br/>

</body>
</html>

2. You can use @exceptionhandler to intercept exceptions for a particular controller and return a JSON data, but you can also define all of the controllers to intercept exceptions.

@ControllerAdvice(basepackageclasses = foocontroller.class)
Public class foocontrolleradvice extends responseentityexceptionhandler {

@ExceptionHandler(Yourexception.class)
@ResponseBody
Responseentity<?> handlecontrollerexception (httpservletrequest request, throwable ex) {
Httpstatus status = GetStatus (request);
return NewResponseentity<> (NewCustomerrortype (Status.value (), Ex.getmessage ()), status);
}

PrivateHttpstatusGetStatus(HttpServletRequest request) {
Integer statusCode = (integer) request.getattribute ("Javax.servlet.error.status_code");
if(StatusCode = =NULL) {
returnHttpstatus.internal_server_error;
}
returnHttpstatus.valueof (StatusCode);
}
}

3. You can also customize the server error page

@Bean
PublicEmbeddedservletcontainercustomizerContainercustomizer(){
return NewMycustomizer ();
}

// ...

Private Static class Mycustomizer implements Embeddedservletcontainercustomizer {

@Override
Public void Customize(Configurableembeddedservletcontainer Container) {
Container.adderrorpages (NewErrorPage (Httpstatus.bad_request,"/500"));
}
}

Spring Boot exception handling (GO)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.