我正在调用外部API,如果状态代码不是确定,我希望将结果“按原样”返回给用户:
1,Formerly free software
2,Formerly proprietary software
3,Freeware
4,Oracle software
5,Proprietary cross-platform software
6,Proprietary database management systems
7,Proprietary operating systems
8,Proprietary version control systems
9,Proprietary wiki software
10,Shareware
11,VMware
12,Warez
如果状态代码不是OK,我怎样才能“原样”返回响应而不执行以下操作:
val connectionFlow: Flow[HttpRequest, HttpResponse, Future[Http.OutgoingConnection]] =
Http().outgoingConnection("akka.io")
def responseFuture: Future[HttpResponse] =
Source.single(HttpRequest(uri = "/"))
.via(connectionFlow)
.runWith(Sink.head)
val fooRoutes = path("foo"){
get {
complete(
responseFuture.flatMap{ response =>
case OK =>
Unmarshal(response.entity.withContentType(ContentTypes.`application/json`)).to[Foo]
case _ => response //fails
})}}
答案 0 :(得分:3)
我认为可能有不同的有效解决方法,可以使用onComplete
指令:
val fooRoutes = path("foo"){
get {
onComplete(responseFuture) {
case Success(response) if response.status == OK =>
complete(Unmarshal(response.entity.withContentType(ContentTypes.`application/json`)).to[Foo])
case Success(response) => complete(response)
case Failure(ex) => complete((InternalServerError, s"An error occurred: ${ex.getMessage}"))
}
}
}