Workaround ClientAbortException and IOException

rest_jersey2_client_abort_exception_thumb

This tutorial provides a workaround for the ClientAbortException (IOException) that may occur when writing output streams via a Response in a Jersey REST web service. There is a previous post dealing with video streaming where you can find the Github repository in a working example.

1. ClientAbortException

The stack trace for the ClientAbortException looks like this:

The ClientAbortException occurs when sending a Response to a client and the client closes the connection before all (stream) data was transmitted.

2. Workaround for ClientAbortException

This exception is not catchable in the REST endpoint, hence we propose the workaround.

2.1 Disable internal Jersey logger

One answer in the web is to disable the internal Jersey logger:

Since this disables all the internal Jersey exceptions and results in the loss of important exceptions, we found another way to go.

2.2 WriterInterceptor

You can detect, intercept and ignore exceptions using a WriterInterceptor. In our case, we want to ignore only the ClientAbortException.

This class uses the org.apache.commons.io.output.ProxyOutputStream from the Apache Commons IO library. If you are working with Tomcat, use the org.apache.catalina.connector.ClientAbortException instead of calling the setOutputStream method. Therefore removing the need for the two nested classes and the dependency on org.apache.commons.io.output.ProxyOutputStream.

You can register the ClientAbortExceptionWriterInterceptor in your web.xml or a ResourceConfig class. In the web.xml, simply add the following init parameters in your servlet configuration.

Using the ResourceConfig as class:

Nevertheless you have to register that ResourceConfig in your web.xml as well:

We recommend the second approach to register multiple components like filters, interceptors and web services. For just testing you can register the Interceptor in the web.xml directly.

3. Conclusion

Following these steps should remove the ClientAbortException and therefore clear up your logging output. Keep in mind that this workaround ignores the exception. This is not a proper way in terms of catching and handling exceptions. But since the server basically has no influence whether the client closes the connection early, there is not much you can do (or handle the exception) anyways.

If you have problems or errors, feel free to comment and ask.

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply