【问题标题】:How to use option(error = ) with a custom function and still make the script abort (in R)如何将 option(error = ) 与自定义函数一起使用并且仍然使脚本中止(在 R 中)
【发布时间】:2019-09-02 19:38:17
【问题描述】:

谁能指出正确使用option(error = function(...){}) 的最佳方式?我想将错误写入日志文件,然后像往常一样终止。目前我使用

  options(error = function(...) {
    #... write to logfile ...
    options(error = NULL)
    stop(geterrmessage())
  })

但重新设置选项并再次调用stop() 对我来说似乎是一种黑客行为。我也试过q("no", status = 1, runLast = FALSE)(来自stop()的文档),但这似乎不等同于普通的stop()。例如,在 RStudio 服务器中,它会退出整个会话。

我需要使用option() 而不是tryCatch(),因为我想捕获脚本中可能出现的所有错误。我通过 cron 作业启动我的脚本,并且我想在脚本失败后立即获得电子邮件/日志条目。

【问题讨论】:

    标签: r error-handling options


    【解决方案1】:

    tryCatch 块可能是这种情况的最佳选择。

    tryCatch({
      #... main code to run ...
    
    }, warning = function(w) {
      #... code to run if any warnings occur ...
      warning(w) # Show the warning
    
    }, error = function(e) {
      #... write to log file ...
      stop(e) # Stop script and show error message. Delete this line if you do not want to stop script
    
    }, finally = {
      #... code to run whether or not error occurs ...
    })
    

    【讨论】:

    • 谢谢,但我知道 tryCatch,但我确实需要为整个脚本设置错误处理程序(我将对我的原始问题添加一些说明)。我希望捕获所有错误,而不仅仅是我可以预期的错误。我想我可以将整个脚本包装在一个 tryCatch 块中,但这甚至不如我当前的解决方案好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2013-06-06
    • 2011-08-05
    • 1970-01-01
    相关资源
    最近更新 更多