使用recoverWith方法

时间:2015-12-15 19:39:12

标签: scala

我正在尝试在服务调用上编写通用恢复处理程序,如下所示。

def handleServerResponse(payLoad: PayLoad): Future[WSResponse] = {
  payLoad.callType match {
    case postJson => broker.postJson(payLoad.url, payLoad.data, payLoad.hadler).recoverWith {
      //How to use recoverHandler?
    }
    case getJson => broker.getJson(payLoad.url, payLoad.mapper).recoverWith {
      //How to use recoverHandler?
    }
    case delete => broker.delete(payLoad.url).recoverWith {
      //How to use recoverHandler?
    }

  }
}

def recoverHandler(): Future[WSResponse] = {
  case ex: ForbiddenException =>
    Logger.error(s"Forbidden to access.  Not going to retry.", ex)
    Future.failed(new NoRetryException("foo", ex))
  case ex: Throwable =>
    Logger.error(s"Received error.  Will retry later.", ex)
    Future.failed(new RetryExternalException("foo", ex))
} 

但我不知道如何在上面的例子中使用recoverHandler()。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

recoverWith方法期望部分函数,​​因此您需要声明处理程序方法:

def recoverHandler(): PartialFunction[Throwable,Future[WSResponse]] = {
  case ex: ForbiddenException =>
    Logger.error(s"Forbidden to access.  Not going to retry.", ex)
    Future.failed(new NoRetryException("foo", ex))
  case ex: Throwable =>
    Logger.error(s"Received error.  Will retry later.", ex)
    Future.failed(new RetryExternalException("foo", ex))
} 

然后,您可以像以下一样使用它:

broker.delete(payLoad.url) recoverWith recoverHandler

broker.delete(payLoad.url).recoverWith(recoverHandler)