Scala 如何以编程方式执行拒绝处理程序的路由并获得结果HttpEntity?
如何以编程方式执行拒绝处理程序的Scala 如何以编程方式执行拒绝处理程序的路由并获得结果HttpEntity?,scala,spray,akka-http,Scala,Spray,Akka Http,如何以编程方式执行拒绝处理程序的Route,并获得结果HttpEntity 例如,假设我有RequestContext对象和Rejection对象,我想对其执行RejectionHandler.default,并获取HttpEntity 下面是我想做的示例: implicit def myRejectionHandler = RejectionHandler.newBuilder() .handleAll[Rejection] { rejections ⇒ def pref
Route
,并获得结果HttpEntity
例如,假设我有RequestContext
对象和Rejection
对象,我想对其执行RejectionHandler.default
,并获取HttpEntity
下面是我想做的示例:
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")
}
val route: Route = extractRequestContext { ctx =>
mapResponseEntity(prefixEntity) {
// Here I want result of `complete` route from RejectionHandler.default
}
}
route
}
.handleNotFound {
complete((NotFound, "Not here!"))
}
.result()
我想我知道你想要什么了。您只需在注释所在的位置应用默认的拒绝处理程序。唯一的问题是,
apply
返回一个选项
,如果遇到的拒绝没有影响到拒绝处理程序中的任何内容,该选项将为None
。这不太可能,因为您使用的是默认处理程序,它几乎可以处理所有事情,但是您仍然需要在代码中说明它(因此mygetOrElse
会导致一个通用的InternalServerError
)。修改后的代码如下所示:
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")
}
val route: Route = extractRequestContext { ctx =>
mapResponseEntity(prefixEntity) {
defaultRejectionHandler.apply(rejections).getOrElse{
complete(StatusCodes.InternalServerError)
}
}
}
route
}
.handleNotFound {
complete((NotFound, "Not here!"))
}
.result()
这是可以编译的,但我并没有实际测试它,看看我们是否得到了预期的效果。另外,我不需要
RequestContext
值ctx
,因此您可以删除其中的extractRequestContext
层。您可以提供一个代码示例来说明这一点吗。它不需要编译。我只需要理解代码流。