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

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

问题描述

我从一些人那里听说在 Scala 中我们倾向于(像其他函数式语言一样)不破坏控制流......相反,按照惯例,我们在 Either Left<中返回错误/代码>.

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.

但是我们如何从该异常中获取 stracktrace 呢?现在我在左边返回一个简单的 Error 案例类,带有代码、消息和原因(Error 也是).但是如果我有错误,我就无法获得堆栈跟踪.如果我的应用程序变得复杂,可能很难找到返回那个 Error 的代码块......根本原因是必不可少的.

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?

我应该在我的 Left 中返回 java 类型 ExceptionThrowable 而不是自定义 Error?在不丢失堆栈跟踪和原因等重要信息的情况下,Scala 异常处理的最佳实践是什么?

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?

推荐答案

我建议使用 Either[java.lang.Throwable, A](其中 Throwable 仍然允许您访问堆栈跟踪),和(通常)使您的自定义错误类型扩展 java.lang.Exception.

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.

这是 Dispatch 0.9 使用的做法,例如,其中 Either[Throwable, A] 用于表示可能失败的计算,自定义错误类型如下所示:

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 7Validation.fromTryCatch(a: => T) 还返回一个 Validation[Throwable, T],其中 Validation 大致相当于 Either.

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

这篇关于使用Either -&gt;处理失败堆栈跟踪在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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