R 记录警告并继续执行 [英] R Log warnings and continue execution

查看:35
本文介绍了R 记录警告并继续执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含在 tryCatch 语句中的 R 代码块.该块中的任何行都可能引发警告或错误.当被捕获时,我有警告和错误的处理程序,它们在两种情况下都执行日志记录,并在错误情况下退出处理.

I have a block of R code that is wrapped in a tryCatch statement. Any of the lines in that block can potentially throw a warning or an error. When caught, I have handlers for both warnings and errors, which perform logging in both cases, and exit handling in the error case.

但在警告的情况下,我只想记录警告,并继续正常执行.目前,当警告被捕获时,它会被记录下来,但执行也会停止.是否有一种简单的方法可以实现此功能?

But in the warning case, I just want the warning to be logged, and the execution to continue as normal. At the moment, when warning is caught, it is logged, but the execution is also stopped. Is there an easy way to allow for this functionality?

推荐答案

不确定这是否是最惯用的解决方案,但使用 tryCatchwithCallingHandlers 的组合适用于我处于几乎相同的情况.

Not sure if it's the most idiomatic solution, but using a combination of tryCatch and withCallingHandlers works for me in an almost identical situation.

我用 withCallingHandlers 包装了对我的函数的调用,提供了一个处理警告的函数;函数的执行将在之后继续.我把所有的那个都包装在了tryCatch中,提供了一个处理错误的函数.

I wrap the call to my function with withCallingHandlers, providing a function to handle warnings; execution of the function will continue afterwards. I wrap all of that in tryCatch, providing a function to handle errors.

tryCatch(
    withCallingHandlers(doSomething(), warning = function(w) logWarning(w)),
    error = function(e) logError(e)
)

感谢 nicola 对 withCallingHandlers 提示的评论.

Thanks to nicola in the comments for the withCallingHandlers tip.

这篇关于R 记录警告并继续执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆