Handling failures with Either -> Where is the stacktrace?

耗尽温柔 提交于 2019-12-10 02:26:34

问题


I heard from some people that in Scala we tend (like other functional languages) to not break the control flow... Instead by convention we return the error in an Either Left.

But how do we get the stracktrace from that exception? For now i return in the Left a simple Error case class with a code, message and cause (Error too). But if i have an error, i can't get the stacktrace. If my application become complexe it may be hard to find the code block that returned that Error... The root cause is essential.


So what do we do in practice?

Should i return, instead of a custom Error, the java type Exception or Throwable in my Left? What's the best practice for Scala exception handling without loosing important informations such as the stacktrace and the cause?


回答1:


I'd suggest using Either[java.lang.Throwable, A] (where Throwable still gives you access to the stack trace), and (in general) making your custom error types extend java.lang.Exception.

This is the practice used by Dispatch 0.9, for example, where Either[Throwable, A] is used to represent computations that may fail, and the custom error types look like this:

case class StatusCode(code: Int)
  extends Exception("Unexpected response status: %d".format(code))

Scalaz 7's Validation.fromTryCatch(a: => T) also returns a Validation[Throwable, T], where Validation is roughly equivalent to Either.



来源:https://stackoverflow.com/questions/12449950/handling-failures-with-either-where-is-the-stacktrace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!