I have the following function:
fun = function(expr) {
mc = match.call()
env = as.environment(within(
list(),
expr = eval(mc$expr)
))
return(env)
}
该函数在tryCatch()
中被调用,以便优雅地处理expr
中的任何错误条件。
它可以很好地处理标准错误条件:
tryCatch({
fun({
stop('error')
})
}, error = function(e) {
message('error happened')
})
# error happened
然而,它无法捕获testthat
的预期错误(这在我的特定用例中是首选):
library(testthat)
tryCatch({
fun({
expect_true(FALSE)
})
}, error = function(e) {
message('expectation not met')
})
# Error: FALSE isn't true.
或者更简单地说:
library(testthat)
tryCatch({
expect_true(FALSE)
}, error = function(e) {
message('expectation not met')
})
# Error: FALSE isn't true.
期望错误未被捕获。
在从R 3.2.2升级到R 3.3.0后出现了这个问题 - 即在R 3.2.2中完全捕获了期望错误。
是否有方法可以使
tryCatch()
在R 3.3.0中捕获testthat
期望?
expect_xxx
函数调用expect
,而expect
又调用withRestarts
。我不确定它的确切作用,但似乎这是你遇到问题的根源。 - Dason