我有一个写得不好的函数。
例如
foo <- function (x) {
y = log(x)
if (y > 1) {
print("hello")
}
}
我用负x参数调用函数。
foo (-1)
当调用负数时,由于日志的行为,我收到了一个错误和警告。
Error in if (y > 1) { : missing value where TRUE/FALSE needed
In addition: Warning message:
In log(x) : NaNs produced
我想用";评估";作用
此:
output <- evaluate(foo(-1))
不起作用。我只是在控制台中收到了相同的警告+错误消息。";输出";对象未创建。
如何捕获错误和警告消息?
您可以从evaluate
中查看try_capture_stack
。这允许你做:
e <- suppressWarnings(try_capture_stack(foo(-1), env = parent.frame()))
if(is.error(e)) print(e$message) else print(e)
#> [1] "missing value where TRUE/FALSE needed"
e <- suppressWarnings(try_capture_stack(foo(5), env = parent.frame()))
if(is.error(e)) print(e$message) else print(e)
#> [1] "hello"
引用输入:
foo <- function (x) {
y = log(x)
if (y > 1) {
print("hello")
}
}
foo (-1)
#> Warning in log(x): NaNs produced
#> Error in if (y > 1) {: missing value where TRUE/FALSE needed
output <- evaluate::evaluate("foo (-1)")
output
#> [[1]]
#> $src
#> [1] "foo (-1)"
#>
#> attr(,"class")
#> [1] "source"
#>
#> [[2]]
#> <simpleWarning in log(x): NaNs produced>
#>
#> [[3]]
#> <simpleError in if (y > 1) { print("hello")}: missing value where TRUE/FALSE needed>
问候,