failWith

Signature

def failWith(error: Throwable): StandardRoute

Description

Bubbles up the given error through the route structure where it is dealt with by the closest handleExceptions directive and its ExceptionHandlerExceptionHandler.

failWith explicitly raises an exception that gets bubbled up through the route structure to be picked up by the nearest handleExceptions directive. Using failWith rather than simply throwing an exception enables the route structure’s Exception Handling mechanism to deal with the exception even if the current route is executed asynchronously on another thread (e.g. in a Future or separate actor).

If no handleExceptions is present above the respective location in the route structure the top-level routing logic will handle the exception and translate it into a corresponding HttpResponseHttpResponse using the in-scope ExceptionHandlerExceptionHandler. See the Exception Handling chapter for more details.

There is one notable special case: If the given exception is a RejectionErrorRejectionError exception it is not bubbled up, but rather the wrapped exception is unpacked and “executed”. This allows the “tunneling” of a rejection via an exception.

Example

Scala
sourceval route =
  path("foo") {
    failWith(new RuntimeException("Oops."))
  }

// tests:
Get("/foo") ~> Route.seal(route) ~> check {
  status shouldEqual StatusCodes.InternalServerError
  responseAs[String] shouldEqual "There was an internal server error."
}
Java
sourceimport static akka.http.javadsl.server.Directives.failWith;
import static akka.http.javadsl.server.Directives.path;

final Route route = path("foo", () ->
  failWith(new RuntimeException("Oops."))
);

// tests:
testRoute(route).run(HttpRequest.GET("/foo"))
  .assertStatusCode(StatusCodes.INTERNAL_SERVER_ERROR)
  .assertEntity("There was an internal server error.");
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.