简体   繁体   中英

Scala / Spray: Return all rejections as JSON

I'm writing a JSON API using Spray 1.2.1 and I would like to return all HTTP Responses in the following format by default.

{ "type":"error", "status":404, "message":"Not Found" }

My own custom rejections / exceptions will have less generic content in the 'message' field, but I'm looking for a way of globally formatting (and possibly otherwise decorating, for debug/testing) all non-2xx responses.

Is this possible without handling every possible rejection and status code?

Thanks!

Sam

I don't know if this is generic enough for you but here's how I do something similar:

import spray.json.DefaultJsonProtocol

case class Rejection(type:String, status: Int, message: String)

object RejectionJsonProtocol extends DefaultJsonProtocol{
   implicit val rejectionFormat = jsonFormat3(Rejection)
}

Then you can complete your routes with a Rejection, possibly in your RouteExceptionHandler like this:

trait RouteExceptionHandlers extends HttpService {

  import RejectionJsonProtocol._

  implicit def routeExceptionHandler(implicit log: LoggingContext) = ExceptionHandler {
    case e: UnsuccessfulResponseException =>
      requestUri { uri =>
        complete(e.response.status, Rejection("error",e.response.status,"Not found"))
      }
  }
    //other exceptions go here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM