Error Routing
You may register an error handler for a specific Throwable in the Routing.Builder method.
Routing routing = Routing.builder()
.error(MyException.class, (req, res, ex) -> {
// handle the error, set the HTTP status code
res.send(errorDescriptionObject);
})
.build- Registers an error handler that handles
MyExceptionthat are thrown from the upstream handlers - Finishes the request handling by sending a response
Error handlers are called when
an exception is thrown from a handler
req.next(ex)is called, whereexis an instance ofThrowable
As with the standard handlers, the error handler must either
send a response
.error(MyException.class, (req, res, ex) -> { res.status(Http.Status.BAD_REQUEST_400); res.send("Unable to parse request. Message: " + ex.getMessage()); })content_copyor, forward the error handling to the downstream error handlers
.error(Throwable.class, (req, res, ex) -> { // some logic req.next(ex); })content_copy
Error handling can’t be forwarded to the standard handlers. In fact, invoking req.next(ex) or req.next() in an error handler are equivalent.
.error(Throwable.class, (req, res, ex) -> {
if (condition) {
req.next(ex);
} else {
req.next();
}
})- Call a downstream error handler with the
Throwableinstance. - Here,
req.next()is the same asreq.next(ex). In both cases, the downstream error handler is called.
Default error handling
If no user-defined error handler is matched, or if the last error handler of the exception called req.next(), then the exception is translated to an HTTP response as follows:
Subtypes of
HttpExceptionare translated to their associated HTTP error codes.Reply with the406HTTP error code by throwing an exception(req, res) -> throw new HttpException("Amount of money must be greater than 0.", Http.Status.NOT_ACCEPTABLE_406)content_copyOtherwise, the exceptions are translated to an Internal Server Error HTTP error code
500.