我有以下代码来处理来自其余调用的响应.我试图将各种HTTP代码从服务器转换为自定义异常,以便调用者可以处理它.
def handleResponse(eventualResponse: Future[WSResponse]): Future[WSResponse] = eventualResponse.map { response => response.status match { case x if x >= 200 && x <= 204 => response case x if x==403 => Future.failed(new RetryExternalException(s"Retryable Exception ${response.status} - ${response.body}")) case x if x >= 500 => Future.failed(new RetryExternalException(s"Retryable Exception ${response.status} - ${response.body}")) case _ => Future.failed(new NoRetryException(s"Non-Retryable Exception ${response.status} - ${response.body}")) } }
但我收到编译错误:
found : scala.concurrent.Future[Nothing] required: play.api.libs.ws.WSResponse
有什么建议吗?
在内部Future#map
,你正在运行一个函数,以防未来成功完成并且预计不会返回一个新的未来(除非你想要一个Future[Future[...]]
.你可以抛出这些异常而不是
def handleResponse(eventualResponse: Future[WSResponse]): Future[WSResponse] = eventualResponse.map { response => response.status match { case x if x >= 200 && x <= 204 => response case 403 => throw new RetryExternalException(s"Retryable Exception ${response.status} - ${response.body}") case x if x >= 500 => throw new RetryExternalException(s"Retryable Exception ${response.status} - ${response.body}") case _ => throw new NoRetryException(s"Non-Retryable Exception ${response.status} - ${response.body}") } }
或使用 flatMap
def handleResponse(eventualResponse: Future[WSResponse]): Future[WSResponse] = eventualResponse.flatMap { response => response.status match { case x if x >= 200 && x <= 204 => Future.successful(response) case x if x==403 => Future.failed(new RetryExternalException(s"Retryable Exception ${response.status} - ${response.body}")) case x if x >= 500 => Future.failed(new RetryExternalException(s"Retryable Exception ${response.status} - ${response.body}")) case _ => Future.failed(new NoRetryException(s"Non-Retryable Exception ${response.status} - ${response.body}")) } }