scala - Scala 非致命示例
问题描述
我正在尝试模拟一种情况,即我的代码抛出了非致命错误,并且在恢复后它会执行其他操作。就像是:
Try {
// do something
} recover {
case NonFatal(e) => println("I want to get to this point")
}
而且我正在尝试使用when(mock.doMethodThatCallsTry).thenThrow(non-fatal)
模拟,但是在查看 scala 文档后,我找不到可以用来模拟这种情况的非致命示例。
解决方案
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以供参考。
您可以抛出任何非致命异常。
推荐阅读
- html - 在分层图像上放置文本
- azure-functions - 是否可以使用功能密钥在 Azure AD B2C 用户旅程中保护 Azure 功能
- node.js - 动态地将名称从表传递到函数定义
- java - 在不使用spring security的情况下在spring boot中获取静态资源的403
- django - 如何过滤我在 ModelChoiceField 字段中使用的查询集?
- php - 导入带有负数但减号是最后一个字符的 txt 文件
- swift - CocoaPods deintegrate 删除工作区文件
- node.js - 提高http请求响应时间
- pandas - 突出 matplotlib 中的政权变化
- java - 如何使用 Stream 填充矩阵?