How to turn all deviations into custom json into a spray?

When spraying (spray.io) causes rejection, it reacts to the body of the string. Since all my API clients assume that my API returns only json, I would like the global conversion to make each rejection a valid json object that matches our error object format. How can i do this?

The format of the error object is as follows:

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

ErrorType is my internal list of enum types like UserNotFound and NeedPaidAccount

+6
source share
1 answer

If you just want to include all the deviations in your custom json format, you can create a deviation handler. For example, I put this in my ServiceActor and do the following:

 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 } } 
+13
source

Source: https://habr.com/ru/post/946554/


All Articles