Created
March 6, 2014 11:29
-
-
Save jrudolph/9387700 to your computer and use it in GitHub Desktop.
Custom rejection handler that returns JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
case class ErrorMessage(message: String, cause: String) | |
object ErrorMessage { | |
import spray.json.DefaultJsonProtocol._ | |
implicit val errorFormat = jsonFormat2(ErrorMessage.apply) | |
} | |
import spray.httpx.SprayJsonSupport._ | |
implicit val jsonRejectionHandler = RejectionHandler { | |
case MalformedRequestContentRejection(msg, cause) :: Nil => | |
complete(StatusCodes.BadRequest, ErrorMessage("The request content was malformed", msg)) | |
// add more custom handling here | |
// default case that wraps the Default error message into json | |
case x if RejectionHandler.Default.isDefinedAt(x) => | |
ctx => RejectionHandler.Default(x) { | |
ctx.withHttpResponseMapped { | |
case resp@HttpResponse(_, HttpEntity.NonEmpty(ContentType(`text/plain`, _), msg), _, _) => | |
import spray.httpx.marshalling | |
resp.withEntity(marshalling.marshalUnsafe(ErrorMessage(msg.asString, ""))) | |
} | |
} | |
} |
This is part of official docs now: http://doc.akka.io/docs/akka-http/current/scala/http/routing-dsl/rejections.html#customising-rejection-http-responses
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jrudolph How can I write same thing for Akka-Http 2.0.2 ? I'd like standard rejection handler to be executed, then take its http status and text and wrap it into my json. Here what I have now:
But turned out
res : RouteResult
is not HttpEntity. How can I get it ?