2016-12-14 84 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