为什么 tryCatch returns 在被要求生成它们时没有警告?

Why tryCatch returns no warnings when it was asked for producing them?

检查以下示例:

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 在被要求时不产生警告?

您创建了对 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