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, "")))
}
}
}
@unoexperto
Copy link

@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:

  implicit def myRejectionHandler =
    RejectionHandler.newBuilder()
      .handleAll[Rejection] { rejections 

      (ctx: RequestContext) => {
        val route: StandardRoute = reject(rejections: _*)

        route.apply(ctx).map { res : RouteResult =>
          println(res)
          res
        }
      }
    }
      .handleNotFound {
        complete((NotFound, "Not here!"))
      }
      .result()

But turned out res : RouteResult is not HttpEntity. How can I get it ?

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