如何将所有拒绝转换为喷涂中的自定义json?

时间:2013-06-05 00:00:07

标签: json scala spray spray-json

当喷雾(spray.io)产生排斥时,它会响应弦体。由于我的所有API客户端都会假设我的API只返回json,我希望全局使每个拒绝都成为符合我们的错误对象格式的有效json对象。我怎样才能做到这一点?

错误对象格式如下所示

{
    'details' : 'Something happened in the app. boooo!',
    'errorType' : 'Unknown'
}

errorType是我的内部枚举式值列表,例如UserNotFoundNeedPaidAccount

1 个答案:

答案 0 :(得分:13)

如果您只想将所有拒绝转换为自定义json格式,则可以创建拒绝处理程序。例如,我会将其放在我的ServiceActor中并执行以下操作:

class ApiServiceActor extends Actor with HttpServiceActor with ApiServices {
  def jsonify(response: HttpResponse): HttpResponse = {
    response.withEntity(HttpBody(ContentType.`application/json`,
      JSONObject(Map(
        "details" -> response.entity.asString.toJson,
        "errorType" -> ApiErrorType.Unknown.toJson
      )).toString()))
  }

  implicit val apiRejectionHandler = RejectionHandler {
    case rejections => mapHttpResponse(jsonify) {
      RejectionHandler.Default(rejections)
    }
  }

  def receive = runRoute {
    yourRoute ~ yourOtherRoute ~ someOtherRoute
  }
}