Customizing Zuul Exception

后端 未结 7 1149
说谎
说谎 2020-11-29 05:23

I have a scenario in Zuul where the service that the URL is routed too might be down . So the reponse body gets thrown with 500 HTTP Status and ZuulException in the JSON bod

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 05:55

    The Zuul RequestContext doesn't contain the error.exception as mentioned in this answer.
    Up to date the Zuul error filter:

    @Component
    public class ErrorFilter extends ZuulFilter {
        private static final Logger LOG = LoggerFactory.getLogger(ErrorFilter.class);
    
        private static final String FILTER_TYPE = "error";
        private static final String THROWABLE_KEY = "throwable";
        private static final int FILTER_ORDER = -1;
    
        @Override
        public String filterType() {
            return FILTER_TYPE;
        }
    
        @Override
        public int filterOrder() {
            return FILTER_ORDER;
        }
    
        @Override
        public boolean shouldFilter() {
            return true;
        }
    
        @Override
        public Object run() {
            final RequestContext context = RequestContext.getCurrentContext();
            final Object throwable = context.get(THROWABLE_KEY);
    
            if (throwable instanceof ZuulException) {
                final ZuulException zuulException = (ZuulException) throwable;
                LOG.error("Zuul failure detected: " + zuulException.getMessage());
    
                // remove error code to prevent further error handling in follow up filters
                context.remove(THROWABLE_KEY);
    
                // populate context with new response values
                context.setResponseBody("Overriding Zuul Exception Body");
                context.getResponse().setContentType("application/json");
                // can set any error code as excepted
                context.setResponseStatusCode(503);
            }
            return null;
        }
    }
    

提交回复
热议问题