如果失败,akka-http 响应传出响应

akka-http responding with outgoing response if failed

我正在调用外部 API,如果状态代码不同于 OK[=17=,我想 return 结果 "AS IS" 给用户] :

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

我怎么能 return 在状态代码不是 OK 的情况下响应 "AS IS" 而不做类似的事情:

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

我认为可能有不同的有效方法来解决这个问题,一个可能是使用 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}"))
      }
    }
  }