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 hidden or 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, ""))) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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