Scala error handling: Try or Either? -
given method in userservice: update
, what's best way handle errors/exceptions here?
option a:
def update(...): try[user]
in way, need define custom exceptions , throw them in function body while needed. of these exceptions business errors (e.g. user_id cannot changed, etc). point here no matter exception(s) thrown (business error, network exception, db io exception, etc), threat them same , return failure(err) - let upper layer handle them.
option b:
def update(...): either[error, user]
this exception-free way. in function body catches possible exceptions , turns them error, , business errors return left[error]
.
using try
seems more natural way me want handle errors. either
more generic thing - either[error, t]
1 special case , think try
invented special case. read should avoid using exceptions error handling...
so, solution better, , why?
there's no silver bullet.
as noted already, try
more specialized version of either
, left
type fixed throwable
.
try
might fit if need materialize exceptions thrown external (perhaps java) libraries, constructor automatically catches them.
another advantage of try
has map
, flatmap
, can use directly in for-comprehensions, whereas either
have explicitly project on right
case. anyway, there's plenty of alternative implementations "right-bias", , scalaz \/
type popular one.
that being said, typically use \/
or equivalent validation
(both scalaz), having ability of returning errors not extend throwable
.
it allows more precise error types, huge win.
Comments
Post a Comment