Failure handling using Either & # 8594; Where is the stack located?

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

But how do we get stracktrace from this exception? At the moment, I am returning to the left a simple Error class with code, message and reason ( Error too). But if I have an error, I cannot get stacktrace. If my application gets complicated, it can be difficult to find the code block that returned this Error value ... The main reason is important.




So what do we do in practice?

Should I return a java Exception or Throwable in my Left instead of a custom Error ? What is the best practice for handling Scala exceptions without losing important information like stacktrace and reason?

+8
java scala exception exception-handling either
Sep 16 '12 at 19:22
source share
1 answer

I would suggest using Either[java.lang.Throwable, A] (where Throwable still gives you access to the stack trace) and (in general) so that your custom error types are extended by java.lang.Exception .

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

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

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

+11
Sep 16 '12 at 19:57
source share
— -



All Articles