Spring Boot 2 Unified exception handling

Source: Internet
Author: User
Tags getmessage throwable

Spring MVC is very straightforward for controller layer exception handling, and using @RestControllerAdvice or @RestControllerAdvice annotations can be light @ Restcontrolleradvice

 Public classGatewayexceptionhandler {/*@ExceptionHandler (exception.class) public Jsonresult handlebusinessexception (HttpServletRequest request,        Exception e) {e.printstacktrace ();        String code = ErrorCodeEnum.SYSTEM_ERROR_STRING.getCode (); String message = Stringutils.isnotempty (E.getmessage ())?        E.getmessage (): "Service currently unavailable";    Return Jsonresult.errorresponse (code, message); }*/@ExceptionHandler (Value= Exception.class)     PublicMap ErrorHandler (Exception ex) {map map=NewHashMap (); Map.put ("Code", 100); Map.put ("MSG", Ex.getmessage ()); returnmap; }}

The following is a note that the Spring Cloud Gateway project overrides the Defaulterrorwebexceptionhandler class to implement custom exception handling

First write a class that inherits the Defaulterrorwebexceptionhandler class, overriding the method

 Public classRmcloudexceptionhandlerextendsDefaulterrorwebexceptionhandler {/*** Create a new {@codeDefaulterrorwebexceptionhandler} instance. *     * @paramerrorattributes the error attributes *@paramresourceproperties The Resources configuration Properties *@paramerrorproperties the error configuration Properties *@paramApplicationContext The current application context*/     PublicRmcloudexceptionhandler (errorattributes errorattributes, ResourceProperties resourceproperties, Errorproperties errorproperties, ApplicationContext applicationcontext) {Super(Errorattributes, ResourceProperties, Errorproperties, ApplicationContext); }    /*** Determine what to return httpstatus * *@paramErrorattributes *@return     */@OverrideprotectedHttpstatus gethttpstatus (map<string, object>errorattributes) {        //httpstatus status = (httpstatus) errorattributes.get ("status"); //return httpstatus.internal_server_error = = status? HttpStatus.OK:status;        returnHttpstatus.ok; }    /*** returned error message JSON content * *@paramRequest *@paramIncludestacktrace *@return     */@OverrideprotectedMap<string, object> geterrorattributes (serverrequest request,Booleanincludestacktrace) {Throwable error = This. GetError (request);        returnJsonresult.responsereturnmap (Rmcloudconstant.gateway_errorcode, This. Buildmessage (Request, error));     }    PrivateString buildmessage (Throwable t) {return"Unknown error!" "; }    PrivateString buildmessage (serverrequest request, Throwable ex) {StringBuilder message=NewStringBuilder ("Api-gateway Failed to handle request [");        Message.append (Request.methodname ()); Message.append (" ");        Message.append (Request.uri ()); Message.append ("]"); if(Ex! =NULL) {message.append (": ");        Message.append (Ex.getmessage ()); }        returnmessage.tostring (); }    Privatehttpstatus determinehttpstatus (throwable error) {returnErrorinstanceofResponsestatusexception?( (responsestatusexception) error). GetStatus (): Httpstatus.internal_server_error; }}

Then, configure the custom Exceptionhandler

Import Com.vcredit.rmcloud.gateway.exception.RmcloudExceptionHandler;
Import Org.springframework.beans.factory.ObjectProvider;
Import org.springframework.boot.autoconfigure.web.ResourceProperties;
Import org.springframework.boot.autoconfigure.web.ServerProperties;
Import org.springframework.boot.context.properties.EnableConfigurationProperties;
Import org.springframework.boot.web.reactive.error.ErrorAttributes;
Import Org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
Import Org.springframework.context.ApplicationContext;
Import Org.springframework.context.annotation.Bean;
Import org.springframework.context.annotation.Configuration;
Import org.springframework.core.Ordered;
Import Org.springframework.core.annotation.Order;
Import Org.springframework.http.codec.ServerCodecConfigurer;
Import Org.springframework.web.reactive.result.view.ViewResolver;

Import java.util.Collections;
Import java.util.List;

/**
* Webflux Global Exception Processor configuration configuration
* Due to Webflux's functional programming, exception handling cannot be achieved by controlleradvice only by adding filter in each routerfunction.
* This is done by injecting a custom errorwebexceptionhandler to achieve global exception handling
*
* @author Lee
*/
@Configuration
@EnableConfigurationProperties ({serverproperties.class, resourceproperties.class})
public class Errorhandlerconfiguration {

Private final serverproperties serverproperties;

Private final ApplicationContext ApplicationContext;

Private final resourceproperties resourceproperties;

Private final list<viewresolver> viewresolvers;

Private final Servercodecconfigurer Servercodecconfigurer;

Public Errorhandlerconfiguration (Serverproperties serverproperties,
ResourceProperties ResourceProperties,
Objectprovider<list<viewresolver>> Viewresolversprovider,
Servercodecconfigurer Servercodecconfigurer,
ApplicationContext ApplicationContext) {
This.serverproperties = serverproperties;
This.applicationcontext = ApplicationContext;
This.resourceproperties = resourceproperties;
This.viewresolvers = Viewresolversprovider
. getifavailable (Collections::emptylist);
This.servercodecconfigurer = Servercodecconfigurer;
}

@Bean
@Order (ordered.highest_precedence)
Public Errorwebexceptionhandler Errorwebexceptionhandler (
Errorattributes errorattributes) {
Rmcloudexceptionhandler Exceptionhandler = new Rmcloudexceptionhandler (
Errorattributes, This.resourceproperties,
This.serverProperties.getError (), this.applicationcontext);
Exceptionhandler.setviewresolvers (this.viewresolvers);
Exceptionhandler.setmessagewriters (This.serverCodecConfigurer.getWriters ());
Exceptionhandler.setmessagereaders (This.serverCodecConfigurer.getReaders ());
return exceptionhandler;
}
}

Jsonresult Content

@Data @noargsconstructor@allargsconstructor Public classJsonresult<t> {    Private StaticString Successcode = ""; PrivateString ErrorCode; PrivateString msg; PrivateT data; PrivateLong timestamp;  Public Static<T> jsonresult<t>successresponse (T data) {return NewJsonresult<> (Successcode, "Success", data, System.currenttimemillis ()); }     Public Static<T> jsonresult<t>errorresponse (String errormessage) {return NewJsonresult<> (Rmcloudconstant.gateway_errorcode, ErrorMessage,NULL, System.currenttimemillis ()); }     Public Static<T> jsonresult<t>errorresponse (String status, String errormessage) {return NewJsonresult<> (Status, ErrorMessage,NULL, System.currenttimemillis ()); }     Public StaticMap<string, object>Responsereturnmap (String status, String errormessage) {Map<string, object> map =NewHashmap<>(); Map.put ("ErrorCode", status); Map.put ("MSG", errormessage); Map.put ("Data",NULL); returnmap; }}

Finally thanks to chenqian56131, the main code is from his github on the Amoy, the above is the actual application of the project, recorded, convenient for later inspection.

Spring Boot 2 Unified exception handling

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.