Akka HTTP客户端请求返回Future [HttpResponse] - 应该如何处理Future失败?只记录错误或将其重新抛给主管?
是否存在可由客户端抛出的错误类型的文档(因此会自动传播到主管)以及可能导致Furure失败的错误。
答案 0 :(得分:2)
这主要是品味问题。我通常会将Future[HttpResponse]
转换为Future[Try[HttpResponse]]
,然后将其作为
response.flatMap { tryResp =>
tryResp match {
case Success(res) =>
res.status match {
case OK =>
// Unmarshal response here into Future[Something]
case Found =>
// Handle redirect by calling requestBlhBlah() again with anotehr URI
case _ =>
// I got status code I didn't expect so I wrap it along with body into Future failure
Unmarshal(res.entity).to[String].flatMap { body =>
Future.failed(new IOException(s"The response status is ${res.status} [${request.uri}] and response body is $body"))
}
}
case Failure(ex) =>
Future.failed(ex)
}
}
如果您使用的是基于流的客户端,您还可以指定Decider
来处理错误
val decider: Decider = {
case ex =>
ex.printStackTrace()
Supervision.Stop // Passes error down to subscriber
}
然后在材质化器中使用它
implicit val materializer = ActorMaterializer(ActorMaterializerSettings(system).withSupervisionStrategy(decider))(system)
或通过.withAttributes(ActorAttributes.supervisionStrategy(decider))
根据Future
失败,由您决定如何处理它。您可以使用recoverWith
将失败转换为其他内容,或将其记录在Future.onFailure
。