首页 > 解决方案 > Scala 非致命示例

问题描述

我正在尝试模拟一种情况,即我的代码抛出了非致命错误,并且在恢复后它会执行其他操作。就像是:

Try {
// do something
} recover {
  case NonFatal(e) => println("I want to get to this point")
}

而且我正在尝试使用when(mock.doMethodThatCallsTry).thenThrow(non-fatal)模拟,但是在查看 scala 文档后,我找不到可以用来模拟这种情况的非致命示例。

标签: scalamockingmockito

解决方案


NonFatal 是定义非致命错误的 scala 对象。这是定义

object NonFatal {
/**
* Returns true if the provided `Throwable` is to be considered non-fatal, or false if it is to be considered fatal
*/
    def apply(t: Throwable): Boolean = t match {
    // VirtualMachineError includes OutOfMemoryError and other fatal errors
    case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false
             case _ => true
     }
     /**
     * Returns Some(t) if NonFatal(t) == true, otherwise None
     */
     def unapply(t: Throwable): Option[Throwable] = if (apply(t)) Some(t) else None
}

这意味着在这种情况下,抛出的每个异常(致命异常除外)都将被捕获

case NonFatal(e) => println("I want to get to this point")

因为在 unapply 中,非致命的例外是 Some(t) 而致命的例外是 None。请参阅https://docs.scala-lang.org/tour/extractor-objects.html以供参考。

您可以抛出任何非致命异常。


推荐阅读