2016-12-14 5 views
1

私は外部のAPIを呼び出していると私は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 
})}} 

私は、1がonCompleteディレクティブを使用することができ、これを解決するための異なる有効な方法があるかもしれません数える

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

答えて

3

:私のような何かをしなくてOK以外のステータスコードの場合には「そのまま」の応答を返すことができ

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

関連する問題