7

I have a RestEasy based service in which I am doing some cleanup work in a ContainerResponseFilter. The problem is that if an unknown runtime exception (i.e. an exception for which I do not have a mapper) is thrown by a resource, the ContainerResponseFilter is never executed.

Is this the expected behavior? Is there a workaround to this? I was looking at the following question (answer by Jonas):
How should I log uncaught exceptions in my RESTful JAX-RS web service?

and that made it seem like the ContainerResponseFilter is executed even when an exception is thrown in the controller?

Am I missing something?

Community
  • 1
  • 1
jay electricity
  • 299
  • 5
  • 15

2 Answers2

0

Didn't work for me either. This claims it should work: https://github.com/Graylog2/graylog2-server/issues/1826

I didn't want to investigate further, and simply use a plain old javax.servlet.Filter, but of course there it's hard to set the reponses-headers (after chain.doFilter(), ... grr..

So used a Spring solution:

public static class MyFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setHeader("MyHeader", "MyValue");
        filterChain.doFilter(request, response);
    }
}
icyerasor
  • 4,973
  • 1
  • 43
  • 52
0

Base on the source code of SynchronousDispatcher in RestEasy.

    protected void writeResponse(HttpRequest request, HttpResponse response, Response jaxrsResponse) {
    try {
        ServerResponseWriter.writeNomapResponse((BuiltResponse)jaxrsResponse, request, response, this.providerFactory);
    } catch (Exception var5) {
        this.writeException(request, response, var5);
    }

}


    public void writeException(HttpRequest request, HttpResponse response, Throwable e) {
    if (response.isCommitted()) {
        throw new UnhandledException("Response is committed, can't handle exception", e);
    } else {
        Response handledResponse = (new ExceptionHandler(this.providerFactory, this.unwrappedExceptions)).handleException(request, e);
        if (handledResponse == null) {
            throw new UnhandledException(e);
        } else {
            try {
                ServerResponseWriter.writeNomapResponse((BuiltResponse)handledResponse, request, response, this.providerFactory);
            } catch (Exception var6) {
                throw new UnhandledException(var6);
            }
        }
    }
}

ContainerResponseFilter will not execute. If you want to set headers when exceptions happen, you need an exception handler to deal with it.

Bensson
  • 4,509
  • 4
  • 19
  • 24