2016-12-14 87 views
1

我调用外部API,我想在不同的状态代码的情况下返回结果“AS IS”用户比OK与传出响应响应:阿卡-HTTP如果失败

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 
})}} 

如何我可以返回的响应中的不是OK状态代码的情况下“按原样”做喜欢的事:

Unmarshal(response.entity).to[String].flatMap { body => 
Future.failed(new IOException(s"The response status is ${response.status} response body is $body"))} 

回答

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}")) 
     } 
    } 
    } 
+0

谢谢,看起来像一个有效的解决方案。 – igx