3

I have a web service running embedded Undertow, and some of the handlers make use of the common Undertow pattern of offloading requests to worker threads:

if (exchange.isInIoThread()) {
    exchange.dispatch(this);
}

This is great for performance, but it presents a problem in dealing with error handling. I created a custom ErrorHandler that maps Java exceptions to HTTP response types and log levels, and allows the API handlers themselves to just bubble up exceptions and not worry about handling them. Unfortunately for requests that are dispatched to a worker thread, they never make it into the ErrorHandler, always resulting in a 500 error if they throw an exception. Is there any way to catch exceptions thrown from worker threads, or do I have to implement exception handling in each API handler?

Jared
  • 2,043
  • 5
  • 33
  • 63
  • You can set `UncaughtExceptionHandler` per thread to handle the exception thrown by threads – Saravana Jun 10 '16 at 17:19
  • The handler needs access to the HttpServerExchange for the failed request. It would be possible to pass that in if I control the code for all of the handlers, but there are a lot of built-in handlers that get used such as https://github.com/undertow-io/undertow/blob/master/core/src/main/java/io/undertow/security/handlers/AuthenticationCallHandler.java#L46. – Jared Jun 10 '16 at 18:14

1 Answers1

2

I wound up adding a handler early in the chain that dispatches the request to a worker thread immediately. Then I added my error handling logic outside the exchange.isInIoThread() check, ensuring that the error handler and the handler that threw the exception are always on the same thread.

Jared
  • 2,043
  • 5
  • 33
  • 63