Scala error handling: try or Either?

Given the method in UserService: update , what's the best way to handle errors / exceptions here?

Option A:

 def update(...): Try[User] 

Thus, I need to define my custom exceptions and throw them into the function body when necessary. Most of these exceptions are business errors (for example, user_id cannot be changed, etc.). It doesn’t matter what kind of exception (business error, network exception, database database exception, etc.), process them the same way and simply return Failure(err) - let the upper level handle them.

Option B:

 def update(...): Either[Error, User] 

This is an exception. In the body of the function, it catches all possible exceptions and turns them into Error, and for business errors, it simply returns Left[Error] .

Using Try seems more natural to me as I want to handle errors. Either is a more general thing - Either[Error, T] is just one special case, and I think Try invented for this special case. But I also read that we should avoid using exceptions to handle errors ...

So which solution is better and why?

+5
source share
1 answer

There is no silver bullet.

As you already noted, Try is just a more specialized version of Either , where the Left type is bound to Throwable .

Try might be a good fit if you need to materialize the exceptions thrown by external (possibly java) libraries, as its constructor automatically catches them.

Another advantage of Try is that it has map and flatMap , so you can use it directly in for-comprehensions, while with Either you have to explicitly design in case of right . In any case, there are many alternative implementations with "right shift", and probably the type scalaz \/ is the most popular.

In doing so, I usually use \/ or the almost equivalent Validation (both from scalaz), since I like being able to return errors that are not Throwable .

It also allows for more accurate types of errors, which is a huge win.

+5
source

Source: https://habr.com/ru/post/1207806/


All Articles