在我正在编写的API中,即使在出现错误的情况下,我也想要返回并返回JSON。我试图找出如何保留所有default
RejectionHandler
行为,但将状态代码和文本转换为JSON对象。由于缺省行为是在函数调用中指定的,而不是数据结构,似乎唯一的方法是将其生成的结果转换为HttpEntity
。有没有简单的方法来做到这一点?在akka-http API中返回JSON错误
1
A
回答
1
我把自己的作品拼凑在一起,但它有一些粗糙的边缘,我不喜欢。 ruslan's answer给了我一些改进的想法。这是我想出的,综合两种方法中最好的:
/**
* Modifies the Akka-Http default rejection handler to wrap the default
* message in JSON wrapper, preserving the original status code.
*
* @param rejectionWrapper wraps the message in a structure to format the
* resulting JSON object
* @param writer writer for the wrapper type
* @tparam WrapperType type of the wrapper
* @return the modified rejection handler
*/
def defaultRejectionHandlerAsJson[WrapperType](rejectionWrapper: String => WrapperType)(implicit writer: JsonWriter[WrapperType]) = {
def rejectionModifier(originalMessage: String): String = {
writer.write(rejectionWrapper(originalMessage)).prettyPrint
}
modifiedDefaultRejectionHandler(rejectionModifier, ContentTypes.`application/json`)
}
/**
* Modifies the Akka-Http default rejection handler, converting the default
* message to some other textual representation.
*
* @param rejectionModifier the modifier function
* @param newContentType the new Content Type, defaulting to text/plain
* UTF-8
* @return the modified rejection handler
*/
def modifiedDefaultRejectionHandler(rejectionModifier: String => String, newContentType: ContentType.NonBinary = ContentTypes.`text/plain(UTF-8)`) = new RejectionHandler {
def repackageRouteResult(entity: ResponseEntity): ResponseEntity = entity match {
// If the entity isn't Strict (and it definitely will be), don't bother
// converting, just throw an error, because something's weird.
case strictEntity: HttpEntity.Strict =>
val modifiedMessage = rejectionModifier(strictEntity.data.utf8String)
HttpEntity(newContentType, modifiedMessage)
case other =>
throw new Exception("Unexpected entity type")
}
def apply(v1: Seq[Rejection]): Option[Route] = {
// The default rejection handler should handle all possible rejections,
// so if this isn't the case, return a 503.
val originalResult = RejectionHandler.default(v1).getOrElse(complete(StatusCodes.InternalServerError))
Some(mapResponseEntity(repackageRouteResult) {
originalResult
})
}
}
2
你可以写这样的事情在你的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 is not found"))
}.result()
其中ErrorResponse
可能是
case class ErrorResponse(error: ErrorInfo)
case class ErrorInfo(code: Int, `type`: String, message: String)
可以为它定义JSON marshallers
。
相关问题
- 1. API Twitter控制台返回错误JSON
- 2. 返回JSON错误
- 3. JSON-RPC应该在返回错误时返回错误吗?
- 4. 如何在asp.net web api中返回json错误消息?
- 5. JSON键值在Python中返回错误
- 6. 在Web API中返回错误
- 7. Django的 - 返回JSON,错误
- 8. 错误返回实体JSON
- 9. Amadeus api返回错误
- 10. Flickr API返回错误403
- 11. Codeigniter API错误返回
- 12. Google play API返回错误
- 13. Recurly API返回500错误
- 14. PHP VoiceCloud API返回错误
- 15. Youtube Javascript API返回错误
- 16. Facebook的api返回错误
- 17. 在发布到CakePHP API时返回错误的JSON视图
- 18. 在JSON中返回错误的Laravel标记错误?
- 19. 在Laravel中返回JSON错误消息作为“错误”对象
- 20. Dojo JSON回调总是返回错误
- 21. Swift3:Openweather API返回零和API错误
- 22. Highrise API正在返回404错误
- 23. 从404上的RESTful Spring API返回错误JSON(模糊@ExceptionHandler)
- 24. 流明API返回422错误时传递正文为JSON
- 25. getJson方法返回一个错误使用woocommerce JSON API插件
- 26. 宝REST API不断返回畸形的JSON错误
- 27. survemonkey api get_survey_list返回错误,“没有JSON对象可以解码”
- 28. 的API层返回JSON编码,我发现了以下错误
- 29. 在Java中返回错误?
- 30. Laravel总是返回json中验证错误的错误包
该死的,这很复杂。大概和我现在解决问题的方式一样复杂。这似乎是缺少API的东西,没有一个更简单的方法。 – acjay
让我知道如果你找到更简单的方法:) – expert