当前位置:  开发笔记 > 编程语言 > 正文

在Scala函数中返回正确的类型

如何解决《在Scala函数中返回正确的类型》经验,为你挑选了1个好方法。

我有以下代码来处理来自其余调用的响应.我试图将各种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

有什么建议吗?



1> knutwalker..:

在内部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}"))
  }
}

推荐阅读
小白也坚强_177
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有