当喷雾(spray.io)产生排斥时,它会响应弦体.由于我的所有API客户端都会假设我的API只返回json,我希望全局使每个拒绝都成为符合我们的错误对象格式的有效json对象.我怎样才能做到这一点?
错误对象格式如下所示
{ 'details' : 'Something happened in the app. boooo!','errorType' : 'Unknown' }
errorType是我的内部枚举式值列表,如UserNotFound和NeedPaidAccount
解决方法
如果您只想将所有拒绝转换为自定义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 } }