【问题标题】:How do I turn all rejections into custom json in spray?如何在喷雾中将所有拒绝转换为自定义 json?
【发布时间】:2013-05-31 12:45:27
【问题描述】:

当 spray (spray.io) 产生拒绝时,它会以字符串体响应。由于我所有的 API 客户端都会假设我的 API 只返回 json,因此我希望在全局范围内将每个拒绝都设为符合我们的错误对象格式的有效 json 对象。我怎样才能做到这一点?

错误对象格式如下所示

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

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

【问题讨论】:

    标签: json scala spray spray-json


    【解决方案1】:

    如果您只想将所有拒绝转换为您的自定义 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
      }
    }
    

    【讨论】:

    • 目前看来fromPF 不存在。 RejectionHandler { 按预期工作。
    猜你喜欢
    • 2014-11-13
    • 1970-01-01
    • 2013-02-15
    • 2021-08-20
    • 2016-12-12
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多