处理失败与 - >堆栈跟踪在哪里? [英] Handling failures with Either -> Where is the stacktrace?

查看:138
本文介绍了处理失败与 - >堆栈跟踪在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一些人那里听到,在Scala中,我们倾向于像其他功能语言那样打破控制流程...而不是按照惯例,我们会在中返回错误。 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆