spring-cloud-netflix icon indicating copy to clipboard operation
spring-cloud-netflix copied to clipboard

how to set response body in a 'post' ZuulFilter

Open leimbag opened this issue 9 years ago • 27 comments

I am doing some data transformation in a custom zuul post-filter, and I use requestContext.setResponseBody(String) does not seem to work, my spring cloud version is Dalston RELEASE, but it works fine at Camden.SR6 version. could you adding example for Dalston RELEASE version ?

leimbag avatar Apr 20 '17 02:04 leimbag

I updated the samples to Dalston and they work fine.

You'll have to provide more details than

does not seem to work

spencergibb avatar Apr 20 '17 02:04 spencergibb

thanks for your relay @spencergibb , I try to test post filter when ResponseStatusCode = 200, use requestContext.setResponseBody(String) and they work fine, buy my post filter want to handle error response, requestContext ResponseStatusCode != 200, for example ResponseStatusCode = 500, and requestContext has a Throwable(such as ZuulException) , I use requestContext.setResponseBody(String) , it does not seem to work. should I remove some requestContext attributes or do something ?

leimbag avatar Apr 20 '17 02:04 leimbag

The RequestContext.setThrowable if only for if a zuul filter throws an exception, not if the proxy request has a 500. I'm afraid I'd need a sample to understand what you're trying to do.

spencergibb avatar Apr 20 '17 02:04 spencergibb

this is my log,and now I add requestContext.remove("throwable"); , they work fine .

[io-26020-exec-1] c.z.d.a.g.f.post.ErrorResponseFilter     : Filter threw Exception

com.netflix.zuul.exception.ZuulException: Filter threw Exception
	at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:227)
	at com.netflix.zuul.FilterProcessor.runFilters(FilterProcessor.java:157)
	at com.netflix.zuul.FilterProcessor.route(FilterProcessor.java:118)
	at com.netflix.zuul.ZuulRunner.route(ZuulRunner.java:96)
	at com.netflix.zuul.http.ZuulServlet.route(ZuulServlet.java:116)
	at com.netflix.zuul.http.ZuulServlet.service(ZuulServlet.java:81)
	at org.springframework.web.servlet.mvc.ServletWrappingController.handleRequestInternal(ServletWrappingController.java:157)
	at org.springframework.cloud.netflix.zuul.web.ZuulController.handleRequest(ZuulController.java:44)
	at org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:50)
	at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
	at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
	at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
	at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
	at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.springframework.boot.web.filter.ApplicationContextHeaderFilter.doFilterInternal(ApplicationContextHeaderFilter.java:55)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:108)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:105)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:106)
	at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:798)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1434)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.cloud.netflix.zuul.util.ZuulRuntimeException: com.netflix.zuul.exception.ZuulException: Forwarding error
	at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.run(RibbonRoutingFilter.java:111)
	at com.netflix.zuul.ZuulFilter.runFilter(ZuulFilter.java:112)
	at com.netflix.zuul.FilterProcessor.processZuulFilter(FilterProcessor.java:193)
	... 64 common frames omitted
Caused by: com.netflix.zuul.exception.ZuulException: Forwarding error
	at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.handleException(RibbonRoutingFilter.java:183)
	at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:158)
	at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.run(RibbonRoutingFilter.java:106)
	... 66 common frames omitted
Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: api-service timed-out and no fallback available.
	at com.netflix.hystrix.AbstractCommand$22.call(AbstractCommand.java:822)
	at com.netflix.hystrix.AbstractCommand$22.call(AbstractCommand.java:807)
	at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:140)
	at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:72)
	at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:72)
	at com.netflix.hystrix.AbstractCommand$DeprecatedOnFallbackHookApplication$1.onError(AbstractCommand.java:1472)
	at com.netflix.hystrix.AbstractCommand$FallbackHookApplication$1.onError(AbstractCommand.java:1397)
	at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:72)
	at rx.observers.Subscribers$5.onError(Subscribers.java:230)
	at rx.internal.operators.OnSubscribeThrow.call(OnSubscribeThrow.java:44)
	at rx.internal.operators.OnSubscribeThrow.call(OnSubscribeThrow.java:28)
	at rx.Observable.unsafeSubscribe(Observable.java:9860)
	at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51)
	at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
	at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
	at rx.Observable.unsafeSubscribe(Observable.java:9860)
	at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:142)
	at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:72)
	at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:72)
	at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:1142)
	at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41)
	at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37)
	at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57)
	at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:1159)
	at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:99)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
	... 1 common frames omitted
Caused by: java.util.concurrent.TimeoutException: null
	at com.netflix.hystrix.AbstractCommand.handleTimeoutViaFallback(AbstractCommand.java:997)
	at com.netflix.hystrix.AbstractCommand.access$500(AbstractCommand.java:60)
	at com.netflix.hystrix.AbstractCommand$12.call(AbstractCommand.java:609)
	at com.netflix.hystrix.AbstractCommand$12.call(AbstractCommand.java:601)
	at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$4.onError(OperatorOnErrorResumeNextViaFunction.java:140)
	... 15 common frames omitted

leimbag avatar Apr 20 '17 03:04 leimbag

@spencergibb must to remove throwable to work ? my post filter code :

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 99;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getResponseStatusCode() != HttpServletResponse.SC_OK;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(HttpServletResponse.SC_OK);
        ctx.getResponse().setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        ctx.getResponse().setCharacterEncoding(CharsetConstants.CHARSET_UTF8);

        Integer errorCode = 500;
        String errorMsg = "Internal Server Error";

        Throwable throwable = (Throwable) ctx.remove("throwable"); // use this line ,it will work fine
//        Throwable throwable = ctx.getThrowable();// use this line cant work, no response body

        if (throwable != null && throwable instanceof ZuulException) {
            logger.error(throwable.getMessage(), throwable);
        }

        ResponseMessage<CommonResponseMessageBody> responseMessageBodyResponseMessage = new ResponseMessage<>();
        responseMessageBodyResponseMessage.setCode(errorCode);
        responseMessageBodyResponseMessage.setMessage(errorMsg);
        try {
            ctx.setResponseBody(objectMapper.writeValueAsString(responseMessageBodyResponseMessage));
        } catch (JsonProcessingException e) {
            String message = String.format("gateway error: cause: %s", e.getMessage());
            logger.error(message);
        }

        return null;
    }

leimbag avatar Apr 20 '17 05:04 leimbag

I don't understand why throwable has anything to do with it.

spencergibb avatar Apr 25 '17 15:04 spencergibb

I don’t know,but remove throwable from ctx, it can work, and in my bootstrap.properties, I set

zuul.SendErrorFilter.error.disable=true

leimbag avatar Apr 26 '17 02:04 leimbag

@leimbag I just tried out the samples and could not find the issue you reported. Looking at the trace you posted, I suspect that your downstream service is timing out. This may well be a route definition issue. Also, the zuul.SendErrorFilter.error.disable should be set to false to let you see the exception.

saiyedzaidi avatar Apr 26 '17 14:04 saiyedzaidi

@saiyedzaidi The purpose of the custom filter is to handle downstream service exceptions,if downstream service is timeing out,I want to catch TimeoutException in filter,and response json of error code and message from the gateway, if I set zuul.SendErrorFilter.error.disable = false,can not to response json message.

leimbag avatar Apr 26 '17 15:04 leimbag

@leimbag that description would have been nice in the initial question. Your filter should then be of type error for Dalston.

spencergibb avatar Apr 26 '17 18:04 spencergibb

@spencergibb I try to set type "error" for Dalston, but no effect. I push the whole project to github, this is link , you can start from register, service, api, gateway, when first access gateway (url= http://localhost:26020/gateway/api/demo/v1/demo/hello?name=spring ), you will get timeout error. If use remove throwable from ctx, you can receive json response, but use getThrowable(), it will nothing to response.

@saiyedzaidi set zuul.SendErrorFilter.error.disable to false , no effect.

leimbag avatar Apr 27 '17 06:04 leimbag

org.springframework.cloud.netflix.zuul.filters.post.SendResponseFilter.shouldFilter() has return context.getThrowable() == null && (!context.getZuulResponseHeaders().isEmpty() || context.getResponseDataStream() != null || context.getResponseBody() != null);

It is not applying when there is a throwable in the context.

saiyedzaidi avatar Apr 27 '17 10:04 saiyedzaidi

@saiyedzaidi if not remove throwable, response message need to extend to SendResponseFilter?

leimbag avatar Apr 27 '17 14:04 leimbag

@spencergibb What would you recommend? Should one create a custom SendResponseFilter of theirs to force a response in this scenario or should SendResponseFilter be modified to to ignore the throwable when a context attribute like ignoreThrowable is found, like below: public boolean shouldFilter() { RequestContext context = RequestContext.getCurrentContext(); return (context.getThrowable() == null || context.get("ignoreThrowable") != null) && (!context.getZuulResponseHeaders().isEmpty() || context.getResponseDataStream() != null || context.getResponseBody() != null); }

saiyedzaidi avatar Apr 28 '17 06:04 saiyedzaidi

@spencergibb I don't know why must judge context.getThrowable() == null ? only judge (!context.getZuulResponseHeaders().isEmpty() || context.getResponseDataStream() != null || context.getResponseBody() != null) is ok ?

leimbag avatar Apr 28 '17 07:04 leimbag

I think the reason is in the method ZuulServlet#service(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse), code source.

The method invokes all zuul filters in order of pre, route, post; if any exception occurs, it will invoke error filters; the end of the whole procedure of ZuulServlet#service is either post filters or error filters. So the last filter(its order is bigger than the other filters who have the same type) of error or post should send response to client directly.

In my opinion, we can't write an error filter who has the biggest order that doesn't send response to client and attempt to delegate it to post filters, due to the case if any exception occurs in the post filters. Otherwise, if we want to do that, we may need to change the upstream code.

And why must judge context.getThrowable() == null in SendResponseFilter? I think it's because of the codes:

            try {
                ...;
            } catch (ZuulException e) {
                error(e);
                postRoute();
                return;
            }

The error filters is invoked before post filter when a ZuulException occurs, so the response has already been sent, the judge context.getThrowable() == null will avoid SendResponseFilter to send response again.

lowzj avatar May 03 '17 12:05 lowzj

We solved a similar use case as described below:

  1. Override ZuulFilterResult runFilter() in your custom ZuulFilter and get the filter execution status.
ZuulFilterResult zuulFilterResult = super.runFilter();
if (zuulFilterResult.getStatus().equals(FAILED)) {
    ctx.set("error.exception", zuulFilterResult.getException());
}
return zuulFilterResult;

This prevents the try-catch shown by @lowzj to enter the catch block because the filter doesn't throw a ZuulException anymore, and hence SendResponseFilter works as expected. Later, we've a post type ExceptionHandlingFilter that does this:

@Override
public boolean shouldFilter() {
    return RequestContext.getCurrentContext().containsKey("error.exception");
}
@Override
public Object run() {
    // do whatever you want
}

After following this discussion, perhaps my code can be modified to not have the first filter handle the exception, but ExceptionHandlingFilter could be of type error and reset the RequestContext.setThrowable after dealing with the exception, thus giving later filters a chance to execute. I'm not sure yet if there's any benefit in doing so.

asarkar avatar May 04 '17 19:05 asarkar

@asarkar If the condition zuulFilterResult.getStatus().equals(FAILED) && zuulFilterResult.getException() != null is true, then the exception of zuulFilterResult will be rethrown by FilterProcessor#processZuulFilter. And then the procedure of ZuulServlet#service will enter the catch block I mentioned above. The related codes in FilterProcessor#processZuulFilter are:

186            Throwable t = null;
...
193            ZuulFilterResult result = filter.runFilter();
194            ExecutionStatus s = result.getStatus();
...
197            switch (s) {
198                case FAILED:
199                    t = result.getException();
...
214            if (t != null) throw t;
...

lowzj avatar May 05 '17 03:05 lowzj

@lowzj zuul.SendErrorFilter.post.disable: true.

asarkar avatar May 05 '17 04:05 asarkar

zuul.SendErrorFilter.post.disable: true

@asarkar It should be:

zuul.SendErrorFilter.error.disable=true

I know this property is to disable SendErrorFilter, but I'm not very clear about why you comment it here. Could you please explain a little more detailed?

lowzj avatar May 05 '17 09:05 lowzj