正确扩展Scala中Java异常的最佳方法是什么?

时间:2013-08-20 08:59:36

标签: scala exception

我正在尝试找到在Scala中扩展Java Exception的最简单但正确的方法。例如,以下内容不正确,因为new Exception(null, cause)new Exception(cause)根据Throwable.java具有不同的行为:

class InvalidVersionException(message: String = null, cause: Throwable = null)
  extends IllegalArgumentException(message, cause) {
  def this(message: String) = this(message, null)
  // This is not same with super(cause)
  def this(cause: Throwable) = this(null, cause)
}

因为我知道Throwable(cause)将邮件设置为cause.toString(),所以我想出了以下内容:

class InvalidVersionException(message: String = null, cause: Throwable = null)
  extends IllegalArgumentException(if ((message eq null) && (cause ne null)) cause.toString else message, cause) {
  def this(message: String) = this(message, null)
  def this(cause: Throwable) = this(null, cause)
}

然而,这仍然有:

if ((message eq null) && (cause ne null)) cause.toString

Throwable.java重复。

有没有更好的方法来扩展Exception而没有任何代码重复?

3 个答案:

答案 0 :(得分:2)

在我看来,您应该能够将仅限原因的构造函数更改为:

def this(cause: Throwable) = this(cause.toString, cause)

编辑:处理无效原因:

def this(cause: Throwable) = this(if (cause == null) "(no message)" else cause.toString, cause)

将“(无消息)”替换为null(不推荐)或您认为合适的任何文本。

答案 1 :(得分:0)

这个怎么样?

trait InvalidVersionException extends IllegalArgumentException

object InvalidVersionException {
  def apply(msg: String) = new IllegalArgumentException(msg) with InvalidVersionException
  def apply(cause: Throwable) = new IllegalArgumentException(cause) with InvalidVersionException
  def apply(msg: String, cause: Throwable) = new IllegalArgumentException(msg, cause) with InvalidVersionException
}

(通过“In Scala, how can I subclass a Java class with multiple constructors?”)

答案 2 :(得分:0)

根据@Shadowlands的回答,我得到了以下结论:

class InvalidVersionException(message: String, cause: Throwable = null)
  extends IllegalArgumentException(message, cause) {
  def this(cause: Throwable) = this(if (cause ne null) cause.toString else null, cause)
  def this() = this(null)
}

..可以节省54个字节。