Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling failures with Either -> Where is the stacktrace?

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?

like image 393
Sebastien Lorber Avatar asked Sep 16 '12 19:09

Sebastien Lorber


1 Answers

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.

like image 157
Travis Brown Avatar answered Sep 29 '22 17:09

Travis Brown