Skip to content

Instantly share code, notes, and snippets.

@monkeymantra
Created December 7, 2017 20:44
Show Gist options
  • Save monkeymantra/fe718c305ba49d9b7c41e51d83dca04e to your computer and use it in GitHub Desktop.
Save monkeymantra/fe718c305ba49d9b7c41e51d83dca04e to your computer and use it in GitHub Desktop.
Respond to a request with a different status code based on a condition applicable to the future
def conditionalResponse[T](
successStatusCode: StatusCodes.Success = StatusCodes.OK,
errorStatusCode: StatusCodes.ServerError = StatusCodes.InternalServerError,
condition: T => Boolean,
fut: => Future[T])(implicit m: ToEntityMarshaller[T]): Route = {
onSuccess(fut) {
case result if condition(result) => complete(successStatusCode -> result)
case result => complete(errorStatusCode -> result)
}
}
@monkeymantra
Copy link
Author

Akka-http doesn't make it super-obvious how to generate different response codes for the same marshallable entity, so here's a utility function to let you generate a route. One might make it more general by changing the signature of condition to T => StatusCode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment