【问题标题】:akka-http responding with outgoing response if failed如果失败,akka-http 将响应传出响应
【发布时间】:2016-12-15 00:48:30
【问题描述】:

我正在调用外部 API,如果状态代码不同于 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 
})}}

在状态码不是 OK 的情况下,如何在不执行类似操作的情况下返回“原样”响应:

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

【问题讨论】:

    标签: scala akka-stream akka-http


    【解决方案1】:

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

    【讨论】:

    • 谢谢,看起来是一个有效的解决方案。
    猜你喜欢
    • 2019-02-04
    • 2022-01-06
    • 2018-07-08
    • 1970-01-01
    • 2020-09-04
    • 2020-06-01
    • 2018-02-19
    • 1970-01-01
    • 2016-01-21
    相关资源
    最近更新 更多