handleExceptions

Signature

def handleExceptions(handler: ExceptionHandler): Directive0

Description

Catches exceptions thrown by the inner route and handles them using the specified ExceptionHandlerExceptionHandler.

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

See Exception Handling for general information about options for handling exceptions.

Example

Scala
val divByZeroHandler = ExceptionHandler {
  case _: ArithmeticException => complete((StatusCodes.BadRequest, "You've got your arithmetic wrong, fool!"))
}
val route =
  path("divide" / IntNumber / IntNumber) { (a, b) =>
    handleExceptions(divByZeroHandler) {
      complete(s"The result is ${a / b}")
    }
  }

// tests:
Get("/divide/10/5") ~> route ~> check {
  responseAs[String] shouldEqual "The result is 2"
}
Get("/divide/10/0") ~> route ~> check {
  status shouldEqual StatusCodes.BadRequest
  responseAs[String] shouldEqual "You've got your arithmetic wrong, fool!"
}
Java
import static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.handleExceptions;
import static akka.http.javadsl.server.Directives.path;

final ExceptionHandler divByZeroHandler = ExceptionHandler.newBuilder()
  .match(ArithmeticException.class, x ->
    complete(StatusCodes.BAD_REQUEST, "You've got your arithmetic wrong, fool!"))
  .build();

final Route route =
  path(PathMatchers.segment("divide").slash(integerSegment()).slash(integerSegment()), (a, b) ->
    handleExceptions(divByZeroHandler, () -> complete("The result is " + (a / b)))
  );

// tests:
testRoute(route).run(HttpRequest.GET("/divide/10/5"))
  .assertEntity("The result is 2");
testRoute(route).run(HttpRequest.GET("/divide/10/0"))
  .assertStatusCode(StatusCodes.BAD_REQUEST)
  .assertEntity("You've got your arithmetic wrong, fool!");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.