Scala error handling: Try or Either?

后端 未结 1 569
渐次进展
渐次进展 2021-01-18 13:15

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

Option A:

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


        
相关标签:
1条回答
  • 2021-01-18 14:05

    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.

    0 讨论(0)
提交回复
热议问题