Should functions returning future [A] exceptions?

I came across functions that return Future , but also immediately throw exceptions. For example, for example:

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

This behavior seems annoying to the caller because you have to do something similar 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 noticed that the WSClient in play structure does this (both throw exceptions if the URL is incorrect, and returns Future , which fails if the HTTP request fails).

Is this a good practice? Is there a better way to handle errors from functions that behave this way?

+8
scala
source share
1 answer

Future used to return something in the end, but it is unclear when this actually happens.

From the .NET perspective (we have Task ): an exception should be thrown if the request is clearly invalid (for example, an invalid URL). You already know this before making a web request, so there is no need to postpone exceptions.

On the other hand, if the server does not work (timeout?) Or the server returns something that your client does not understand: this can and should be processed later, since the answer is not available directly when making the call. We could block until an answer is available, but that will make Future useless.

I think this is best compared to the "Exit early" programming style.

+4
source share

All Articles