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
Copied
  • Registers an error handler that handles MyException that 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, where ex is an instance of Throwable

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());
    })
    Copied
  • or, forward the error handling to the downstream error handlers

    .error(Throwable.class, (req, res, ex) -> {
        // some logic
        req.next(ex);
    })
    Copied

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(); 
    }
})
Copied
  • Call a downstream error handler with the Throwable instance.
  • Here, req.next() is the same as req.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 HttpException are translated to their associated HTTP error codes.

    Reply with the 406 HTTP error code by throwing an exception
    (req, res) -> throw new HttpException("Amount of money must be greater than 0.", Http.Status.NOT_ACCEPTABLE_406) 
    Copied
  • Otherwise, the exceptions are translated to an Internal Server Error HTTP error code 500.