Spring Cloud Zuul Gateway exception handling

Source: Internet
Author: User
Tags throw exception throwable

Spring Cloud Zuul Gateway exception handling

An anomaly test:

1> creates a pre-type filter and throws an exception in the filter's Run method implementation. For example, the following implementation, the DoSomething method called in the Run method throws a RuntimeException exception

 PackageCom.xbchen.springcloud.filter.post;ImportCom.netflix.zuul.ZuulFilter;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.stereotype.Component; @Component Public classThrowexceptionpostfilterextendsZuulfilter {Private StaticLogger log = Loggerfactory.getlogger (throwexceptionpostfilter.class); @Override PublicString FilterType () {return"POST"; } @Override Public intFilterorder () {return10; } @Override Public BooleanShouldfilter () {return true; } @Override PublicObject Run () {Log.info ("This is a post filter, it'll throw a runtimeexception");        DoSomething (); return NULL; }    Private voiddosomething () {Throw NewRuntimeException ("Exist Some errors ..."); }}

2> creating a bean for a filter in the Startup class

@Bean  Public Throwexceptionfilter Throwexceptionfilter () {  returnnew  Throwexceptionfilter () ;}

3> Running the Startup class

4> found that the background did not throw exception information

Two problem analysis:

View the methods in the Postroute phase of the exception handling filter Senderrorfilter Shouldfilter

Note : This issue has been fixed in the new version and the Error.status_code judgment has been canceled.

That is: Only the online text contains Error.status_code, can be senderrorfilter processing.

This requires self-processing.

handling Mode 1: When throwing exceptions, self-capture settings Error.status_code

  @Override  public   Object run () {Log.info ( "This is a post filter, it would throw a runtimeexception"    Span style= "color: #000000");     // dosomething ();     RequestContext context=requestcontext.getcurrentcontext ();     try  {dosomething ();  catch   (Exception e) {Context.set (        "Error.status_code"  "Error.exception", 3 return  null   

processing Mode 2: Add a filter for error handling

@Component Public classErrorfilterextendszuulfilter {Logger log= Loggerfactory.getlogger (errorfilter.class); @Override PublicString FilterType () {return"Error"; } @Override Public intFilterorder () {return20; } @Override Public BooleanShouldfilter () {return true; } @Override PublicObject Run () {RequestContext CTX=Requestcontext.getcurrentcontext (); Throwable Throwable=Requestcontext.getcurrentcontext (). getthrowable (); Log.error ("This is a errorfilter: {}", Throwable.getcause (). GetMessage ()); Ctx.set ("Error.status_code", Httpservletresponse.sc_internal_server_error); Ctx.set ("Error.exception", Throwable.getcause ()); return NULL; }}

Three: Legacy issues: Routing consists of 3 stages, normal process: Preroute-->route-->postroute

Where Preroute and route anomalies, will be captured directly into the Postroute;

Will pass through the Postroute filter (Senderrorfilter extends Zuulfilter)

However, the postroute phase of the exception is not processed by the filter. This requires a separate processing of exceptions for the postroute phase.

Processing method:

New processing class, extended filter Processzuulfilter method for handling class Filterprocessor

 Public classDidifilterprocessorextendsFilterprocessor {@Override PublicObject Processzuulfilter (zuulfilter filter)throwszuulexception {Try {            return Super. Processzuulfilter (filter); } Catch(zuulexception e) {RequestContext ctx=Requestcontext.getcurrentcontext (); Ctx.set ("Failed.exception", E); Ctx.set ("Failed.filter", filter); Throwe; }    }}

To set the processing class in the Startup class

@SpringBootApplication @enablezuulproxy  Public class gatewayapplication {  publicstaticvoid  main (string[] args) {    Filterprocessor.setprocessor (new   didifilterprocessor ());    Springapplication.run (gatewayapplication. class , args);  }
}

Add exception handling filter for post stage

/*** Exception thrown from post, use this filter to return error message*/@Component Public classErrorextfilterextendssenderrorfilter {Logger log= Loggerfactory.getlogger (errorextfilter.class); @Override PublicString FilterType () {return"Error"; } @Override Public intFilterorder () {return30; } @Override Public BooleanShouldfilter () {RequestContext CTX=Requestcontext.getcurrentcontext (); Zuulfilter Failedfilter= (Zuulfilter) ctx.get ("Failed.filter"); if(Failedfilter! =NULL&& Failedfilter.filtertype (). Equals ("POST")) {            return true; }        return false; }}

Four: Exception customization

The above exception has been thrown normally, but the format does not necessarily conform to the project requirements, or sometimes it is not necessary to return the exception to the client.

Because the exception information format is defined in Defaulterrorattributes, this class can be extended.

For example: Exception information, avoid returning to the client.

 Public class extends defaulterrorattributes {    @Override    public map<string, object>  Geterrorattributes (            boolean  includestacktrace) {        MapSuper. Geterrorattributes (Requestattributes, includestacktrace);        Result.remove ("Exception");         return result;}    }


In the startup class, the new exception attribute extends the bean creation of the class.

@Bean    Public defaulterrorattributes errorattributes () {    returnnew  didierrorattributes ();  }

Spring Cloud Zuul Gateway 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.