Given a method in UserService: update
, what's the best way to handle errors/exceptions here?
Option A:
def update(...): Try[User]
In this way, I need to define my custom exceptions and throw them in the function body when needed. Most of these exceptions are business errors (e.g. user_id cannot be changed, etc). The point here is no matter what exception(s) are thrown (business error, network exception, DB IO exception, etc), treat them the same way and just return a Failure(err)
- let the upper layer handle them.
Option B:
def update(...): Either[Error, User]
This is the exception-free way. In the function body it catches all possible exceptions and turns them into Error, and for business errors just return Left[Error]
.
Using Try
seems to be a more natural way to me as I want to handle errors. Either
is a more generic thing - Either[Error, T]
is just one special case and I think Try
is invented for this special case. But I also read that we should avoid using exceptions for error handling...
So, which solution is better, and why?
Either
, because it allows you to be explicit about which error types are possible, rather than the genericThrowable
you get withTry
. As @Gabriele says, I'd prefer scalaz\/
as it has a more usablemap
construct.