【发布时间】:2020-09-15 05:08:14
【问题描述】:
有一个有警告但不影响最终输出的函数。我想将警告捕获到日志中,在控制台上抑制警告消息并返回值。
fn1 <- function() {
warning("this is a warning!")
return(1)
}
我尝试了withCallingHandlers,但警告消息仍然打印出来,tryCatch 阻止返回值。例如,我使用message 假装保存到日志。
withCallingHandlers(expr = fn1(),
warning = function(w) {
message(paste0("saved to a file: ", w$message))
# write(w$message, "xxlocation")
}
)
输出
saved to a file: this is a warning!
[1] 1
Warning message:
In fn1() : this is a warning!
我可以使用重启来抑制警告,但我的返回值也被抑制了。和tryCatch很像:
withCallingHandlers(
withRestarts(fn1(),
mufflewarn=function(msg) {
message(msg)
}),
warning = function(w) {
invokeRestart("mufflewarn", w$message)
}
)
this is a warning!
有什么办法可以输出:
saved to a file: this is a warning!
[1] 1
【问题讨论】:
标签: r error-handling try-catch