Given a method in UserService: update
, what\'s the best way to handle errors/exceptions here?
def update(...): Try[User]
There's no silver bullet.
As you noted already, Try
is simply a more specialized version of Either
, where the Left
type is fixed to Throwable
.
Try
might be a good fit if you need to materialize exceptions thrown by external (perhaps 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, whereas with Either
you would have to explicitly project on the right
case.
Anyway, there's plenty of alternative implementations with a "right-bias", and probably the scalaz \/
type is the most popular one.
That being said, I typically use \/
or the almost equivalent Validation
(both from scalaz), as I like having the ability of returning errors that do not extend Throwable
.
It also allows for more precise error types, which is a huge win.