Adr*_*uez 6 json scala spray spray-json
当喷雾(spray.io)产生排斥时,它会响应弦体.由于我的所有API客户端都会假设我的API只返回json,我希望全局使每个拒绝都成为符合我们的错误对象格式的有效json对象.我怎样才能做到这一点?
错误对象格式如下所示
{
'details' : 'Something happened in the app. boooo!',
'errorType' : 'Unknown'
}
Run Code Online (Sandbox Code Playgroud)
errorType是我的内部枚举式值列表,如UserNotFound和NeedPaidAccount
Adr*_*uez 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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1621 次 |
| 最近记录: |