【发布时间】:2018-09-23 20:51:16
【问题描述】:
在一个函数中,我正在调用另一个计算创新的外部函数,它在某些情况下会触发警告,但也会返回一个值,无论是否发生警告,我都想对其进行评估。
此外,如果发生警告或错误,我想捕获警告/错误消息以进行进一步处理。
以下 R 代码说明了我的意图:
hurz <- function(x) {
# HINT: max(x) triggers a warning when x = NULL
max(x)
return(12345)
}
laus <- function(x) {
r <- tryCatch({
list(value = hurz(x), error_text = "No error.")
}, warning = function(e) {
error_text <- paste0("WARNING: ", e)
# ugly hack to get the result while still catching the warning
return(list(value = (suppressWarnings(hurz(5))), error_text = error_text))
}, error = function(e) {
error_text <- paste0("ERROR: ", e)
return(list(value = NA, error_text = error_text))
}, finally = {
}, quiet = TRUE)
return(r)
}
当发生错误时,代码会在错误捕获部分结束,因此很明显我无法从 hurz() 获取返回值。
但是,似乎没有什么好的方法可以同时获取
- hurz() 的返回值以及
- 产生的警告。
当调用laus(3) 时,我得到以下响应:
$value
[1] 12345
$error_text
[1] "No error."
另一方面,当调用laus(NULL) 时,我得到:
[1] 12345
$error_text
[1] "WARNING: simpleWarning in max(x): no non-missing arguments to max; returning -Inf\n"
当然,调用 hurz() 包裹如上所示的 suppressWarnings 将是一个非常丑陋的 hack,而且是没有选择的,因为 hurz() 执行计算密集型工作。
有没有人知道如何以一种很好的方式解决这个问题,以及如何捕获警告并仍然一次性获得函数的返回值?
【问题讨论】:
标签: r exception-handling return warnings