[英]How to catch exception thrown from Future[HttpResponse] scala
I am new to scala.我是 Scala 的新手。 I am using the HTTP-client of scala to hit another server.
我正在使用 Scala 的 HTTP 客户端访问另一台服务器。 Where the response returned is Future[HttpResponse].
返回的响应是 Future[HttpResponse]。 Here is something that I have:
这是我有的东西:
pathPrefix("run") {
post {
entity(as[InputRequest]) { inputRequest =>
complete {
runService(inputRequest)
}
}
}
}
def runService(inputRequest:InputRequest) : Future[HttpResponse] = {
val pipeline: HttpRequest => Future[HttpResponse] = sendReceive ~> unmarshal[HttpResponse]
val response: Future[HttpResponse] = pipeline(Post("some-hostname", inputRequest)
~> addCredentials(BasicHttpCredentials("user", "pass"))
response
}
So if something fails(like 500 internal server error) from response, How to catch its exception?因此,如果响应失败(例如 500 内部服务器错误),如何捕获其异常?
Couple of ways to do it:有几种方法可以做到:
Using rejection handler directive:使用拒绝处理程序指令:
handleRejections(/*your custom rejection handler || default*/) {
pathPrefix("run") {
...
}
Or recover
Future
:或
recover
Future
:
response.recover {
case t => // t is Throwable, do something with it
}
The return type of your function def runService(inputRequest:InputRequest) : Future[HttpResponse]
will then change depending on what your recover evaluates to您的函数
def runService(inputRequest:InputRequest) : Future[HttpResponse]
的返回类型def runService(inputRequest:InputRequest) : Future[HttpResponse]
然后将根据您的恢复评估结果而改变
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.