处理失败与 - >堆栈跟踪在哪里? [英] Handling failures with Either -> Where is the stacktrace?
问题描述
中返回错误。
Left
。 但是我们如何从该异常中获取stracktrace?
现在我在左边返回一个简单的错误
案例类,其中包含代码,消息和原因(错误
也)但是如果我有一个错误,我不能得到堆栈跟踪。
如果我的应用程序变得复杂,可能很难找到返回错误
的代码块...根本原因。
那么我们在实践中做什么?
如果我返回,而不是自定义错误
,那么java类型 Exception
或
Throwable
在我的左
?
什么是Scala异常处理的最佳做法,而不会丢失重要信息,如堆栈跟踪和原因?
'd建议使用 [java.lang.Throwable,A]
(其中 Throwable
仍然允许您访问堆栈跟踪)和(一般)您的自定义错误类型扩展 java.lang.Exception
。
这是 Dispatch 0.9 ,例如, [Throwable,A]
用于表示可能会失败的计算,自定义错误类型如下所示:
案例类StatusCode(代码:Int)
扩展异常(意外响应状态:%d.format(代码))
Scalaz 7 的 Validation.fromTryCatch(a:=> T)
还返回一个验证[Throwable,T]
,其中验证
大致相当于到
。
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?
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
.
这篇关于处理失败与 - >堆栈跟踪在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!