r - 当需要清除状态时,如何优雅地处理R中的错误?

标签 r error-handling

最好的方法是处理R中的错误?我希望既可以从脚本的最终用户那里提取堆栈跟踪信息,又可以清理我可能正在使用的所有临时变量和状态。

所以我想我的问题有两个方面:

  • 最重要的是,在处理错误时如何正确处理清理状态?
  • 如何从R的错误消息中提取有用的有用信息,而无需内部
    东西被吐出来吗?

  • 此刻,我有一些类似的东西,但是(1)看起来非常糟糕,(2)仍然给我带来了可怕的错误消息。
    # Create some temporary working state and variables to clean up
    file <- "somefile"
    working.dir <- getwd()
    setwd("../")  # Go somewhere else
    saf.default <- getOption("stringsAsFactors")
    options(stringsAsFactors = FALSE)
    
    # Now lets try to open the file, but it doesn't work (for whatever reason)
    # I want to clean up the state, stop, and wrap the error string with a nicer
    # message
    tryCatch({
      # Need to embed the tryCatch because we still need some of the state variables
      # for the error message
      tryCatch({
        f <- read.table(file)
      }, error = function(err.msg) {
        # Can't clean up here, we still need the `file variable!
        stop("Could not open file '", file, "' with error message:\n", print(err.msg), 
             call.=FALSE)
      })
    }, error = function(err.msg) {
      # Now we can clean up state
      setwd(working.dir)
      options(stringsAsFactors = saf.default)
      rm(file, working.dir, saf.default, 
         envir=globalenv())  # This also seems awful?
      stop(print(err.msg), call.=FALSE)
    })
    
    # Do more stuff, get more state, handle errors, then clean up.
    # I.e can't use `finally` in previous tryCatch!
    

    由此产生的错误消息仍然是许多丑陋的内部结构:
    # <simpleError in file(file, "rt"): cannot open the connection>
    # <simpleError: Could not open file 'somefile' with error message:
    # Error in file(file, "rt"): cannot open the connection
    >
    # Error: Could not open file 'somefile' with error message:
    # Error in file(file, "rt"): cannot open the connection
    # In addition: Warning messages:
    # 1: In file(file, "rt") :
    #   cannot open file 'somefile': No such file or directory
    # 2: In stop(print(err.msg), call. = FALSE) :
    #   additional arguments ignored in stop()
    >
    

    最佳答案

    我会将任何状态更改代码隔离到其自己的函数中,并使用on.exit。这保证了清除将发生,无论是否发生错误。

    readFile <- function(.....)
    {
        on.exit({
            setwd(cur.dir)
            options(stringsAsFactors=saf)
        })
        cur.dir <- getwd()
        saf <- getOption("stringsAsFactors")
        setwd("new/dir")
        options(stringsAsFactors=FALSE)
        ....
    }
    

    关于r - 当需要清除状态时,如何优雅地处理R中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17141390/

    相关文章:

    php - 收到警告标题在wordpress上不得包含多个标题

    magento - 使用示例数据安装Magento 2.1.2时“An error has happened during application run.”错误

    php - 如何在PHP中获取 sphinx 连接失败错误

    r - 如何使用 OpenCPU 运行自定义 R 脚本

    r - 在 Rcpp 中创建 R S4 类的对象?

    r - 在 R dplyr 的每一列中获取 1 的百分比

    linux - 防止 R 在 unix/linux 上使用虚拟内存?

    r - 在随时间重复的条件下进行总结

    jquery - 获取 img 请求的响应

    c# - 如何使用 Moq 模拟 SoapException 以单元测试错误处理