为什么tryCatch在被要求生成它们时不会返回警告?

时间:2017-07-18 12:03:04

标签: r testthat

检查以下示例:

library(testthat)
expect_warning(tryCatch(stop("Error!"), error = function(e) warning(e)))
## Error: tryCatch(stop("Error!"), error = function(e) warning(e)) showed 0 warnings
## In addition: Warning message:
## In doTryCatch(return(expr), name, parentenv, handler) : Error!

为什么testthat说没有警告?

使用withWarnings function discussed in here也没有显示任何警告信号。为什么tryCatch在被要求时不会产生警告?

1 个答案:

答案 0 :(得分:2)

您创建了对doTryCatchwithCallingHandlers的嵌套调用。问题是e不是字符,而是simpleError对象(包含对doTryCatch的另一个调用)。以下内容有些作用,但显示了引发警告的实际上下文:

tryCatch(stop("Error!"), error = function(e) warning(e[[1]]))
#Warning message:
#In value[[3L]](cond) : Error!
library(testthat)
expect_warning(tryCatch(stop("Error!"), error = function(e) warning(e[[1]])))
#no further output
相关问题