handleRejections

Description

Using this directive is an alternative to using a global implicitly defined RejectionHandler that applies to the complete route.

See Rejections for general information about options for handling rejections.

Example

final RejectionHandler totallyMissingHandler = RejectionHandler.newBuilder()
  .handleNotFound(complete(StatusCodes.NOT_FOUND, "Oh man, what you are looking for is long gone."))
  .handle(ValidationRejection.class, r -> complete(StatusCodes.INTERNAL_SERVER_ERROR, r.message()))
  .build();

final Route route = pathPrefix("handled", () ->
  handleRejections(totallyMissingHandler, () ->
    route(
      path("existing", () -> complete("This path exists")),
      path("boom", () -> reject(Rejections.validationRejection("This didn't work.")))
    )
  )
);

// tests:
testRoute(route).run(HttpRequest.GET("/handled/existing"))
  .assertEntity("This path exists");
// applies default handler
testRoute(route).run(HttpRequest.GET("/missing"))
  .assertStatusCode(StatusCodes.NOT_FOUND)
  .assertEntity("The requested resource could not be found.");
testRoute(route).run(HttpRequest.GET("/handled/missing"))
  .assertStatusCode(StatusCodes.NOT_FOUND)
  .assertEntity("Oh man, what you are looking for is long gone.");
testRoute(route).run(HttpRequest.GET("/handled/boom"))
  .assertStatusCode(StatusCodes.INTERNAL_SERVER_ERROR)
  .assertEntity("This didn't work.");
The source code for this page can be found here.