Skip to content

Instantly share code, notes, and snippets.

@jrudolph
Created March 6, 2014 11:29
Show Gist options
  • Save jrudolph/9387700 to your computer and use it in GitHub Desktop.
Save jrudolph/9387700 to your computer and use it in GitHub Desktop.
Custom rejection handler that returns JSON
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