Imagine you have a filter that starts a database transaction, processes the request, and then then attempts to commit the transaction.
doFilter(...) {
...
transaction.begin();
filterChain.doFilter(request, response);
transaction.commit();
}
Using Jersey, there are some problems:
- Using a Filter, the Jersey Servlet Container commits/flushes the response before execution returns to your filter. So, if the commit fails, you can't modify the return code to be a failure. Also, exceptions won't be caught by a JAX-RS ExceptionMapper.
Using ContainerRequestFilter/ContainerResponseFilter.
public ContainerRequest filter(ContainerRequest request) { ... }
public ContainerResponse filter(ContainerRequest request, ContainerResponse response) { ... }
This allows exceptions to bubble up to an ExceptionMapper, but splits logic over 2 separate methods/interfaces. The problem is that if there's an exception that doesn't map to a response, the ContainerResponseFilter is never called, so you can't clean up.
What's the preferred way to handle this in a JAX-RS environment? Is there a way to configure the flushing of the response, or is there a class or interface that I'm overlooking?