简体   繁体   English

返回Future [A]的函数是否应该引发异常?

[英]Should functions that return Future[A] throw exceptions?

I have come across functions that return Future but also throw exceptions immediately. 我遇到了返回Future并立即引发异常的函数。 For example like this: 例如这样:

def func(): Future[String] {
  if (something) {
     // this
     Future.failed(new RuntimeException("test"))
  } else {
     // and this
     throw new RuntimeException("test")
  }
}

This behaviour seems annoying for the caller, because you have to do something like this to catch both errors: 这种行为对于调用者来说似乎很烦人,因为您必须执行以下操作才能捕获两个错误:

try {
  func() recover {
    case e: Exception => handleError(e)
  }
} catch {
  case e: Exception => Future.successful(handleError(e)) //or Future.failed etc
}

I have noticed that the WSClient in play framework does this (both throwing exceptions if the URL is malformed, and returning a Future which fails if the HTTP request fails). 我已经注意到WSClient在play框架中可以做到这一点(如果URL格式不正确,都会抛出异常,如果HTTP请求失败,则返回Future )。

Is this good practice? 这是好习惯吗? Is there a better way to handle errors from functions that behave like this? 有没有更好的方法来处理此类行为的错误?

Future is used to return something eventually, but its not clear when this actually happens. Future用于最终返回某些内容,但尚不清楚何时实际发生。

Coming from a .NET perspective (we have Task ): an exception should be thrown if the request is clearly invalid (such as an malformed url). 从.NET角度来看(我们拥有Task ):如果请求明显无效(例如,格式错误的url),则应引发异常。 You already know this before actually making the web request, so there is no need in delaying the exceptions. 在实际发出Web请求之前,您已经知道这一点,因此无需延迟异常。

On the other hand, if the server is down (timeout?) or the server returns something your client doesn't understand: this can and must be handled at a later time, since the response is not directly available when making the call. 另一方面,如果服务器关闭(超时?)或服务器返回了您的客户端不了解的信息:可以并且必须在以后的时间进行处理,因为在进行呼叫时响应不直接可用。 We would be able to block until the response is available, but that would render the Future useless. 我们将能够阻塞直到响应可用,但这将使Future变得毫无用处。

I think this is best compared with the 'Exit early' programming style. 我认为与“早期退出”编程风格相比,这是最好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM