如果您只想将所有拒绝转换为您的自定义 json 格式,您可以创建一个拒绝处理程序。例如,我将其放入 myServiceActor
并执行以下操作:
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
}
}