scala - Return JSON errors in akka-http API -
in api i'm writing, want take , return json, in cases of errors. i'm trying figure out how preserve of default
rejectionhandler
behavior, convert status codes , text json object. default behavior specified within function calls, rather data structure, seems way convert httpentity
of result produces. there simple way this?
you can write in httpservice
private val defaultrejectionhandler = rejectionhandler.default implicit def myrejectionhandler = rejectionhandler.newbuilder() .handleall[rejection] { rejections ⇒ def prefixentity(entity: responseentity): responseentity = entity match { case httpentity.strict(contenttype, data) => { import spray.json._ val text = errorresponse(0, "rejection", data.utf8string).tojson.prettyprint httpentity(contenttypes.`application/json`, text) } case _ => throw new illegalstateexception("unexpected entity type") } mapresponseentity(prefixentity) { defaultrejectionhandler(rejections).getorelse { complete(statuscodes.internalservererror) } } }.handlenotfound { complete(statuscodes.forbidden -> errorresponse(statuscodes.notfound.intvalue, "notfound", "requested resource not found")) }.result()
where errorresponse
possibly
case class errorresponse(error: errorinfo) case class errorinfo(code: int, `type`: string, message: string)
for can defined json marshallers.
Comments
Post a Comment