Scala recover or recoverWith

前端 未结 2 1391
离开以前
离开以前 2020-12-04 16:24

We are developing some systems in our company in Scala and we have some doubts. We were discussing about how to map the future exceptions and we don\'t know when we should u

2条回答
  •  情深已故
    2020-12-04 16:57

    Using recoverWith you are asked to return a wrapped future, using recover you are asked to throw an exception.

    .recoverWith # => Future.failed(t)
    .recover # => throw t
    

    I prefer using recoverWith because I think functional programming prefers returning objects than throwing exceptions which is less of a functional style, even if it's internal code block, I think it still holds..

    However if I have an internal piece of code in the recovery block which might throw an exception then, in that case, rather than catching it and wrapping it with Future, or Trying it, I might as well just run this piece of code in combination with recover and it would handle the exception wrapping for you, which would make the code more readable and compact.

提交回复
热议问题