可靠地识别和处理错误或警告等特定条件

R Y*_*oda 5 error-handling r try-catch

我想通过提供一个功能来处理特定(选定)条件并结合重试功能来改进R错误处理.

例如,循环下载应在超时或连接错误后重试,但在发生其他错误时立即停止.

我找不到可靠的方法来识别特定的情况.

"可靠"我的意思是条件ID或至少不同的条件类.我的问题是:

  1. 基础R抛出的错误条件(以及许多使用的包stop)似乎不使用子类,但(几乎)总是返回simpleError,error并且conditionas class.

  2. 错误消息可能已本地化(不同语言),甚至可能随着新版本的推移而发生变化.

如何独立于R版本,平台(Win,OSX,Linux)和语言设置,可靠地识别基本R或第三方软件包的特定条件?

我假设我无法修改抛出条件的源代码(例如添加子类).

examine_condition <- function(exp) {
  cnd <- tryCatch(exp, error = function(e) e)
  str(cnd)  # show the internals
  invisible(cnd)
}

examine_condition(base::log("a"))
# List of 2
# $ message: chr "non-numeric argument to mathematical function"
# $ call   : language log("a")
# - attr(*, "class")= chr [1:3] "simpleError" "error" "condition"

examine_condition(base::colSums("a"))
# List of 2
# $ message: chr "'x' must be an array of at least two dimensions"
# $ call   : language base::colSums("a")
# - attr(*, "class")= chr [1:3] "simpleError" "error" "condition"

examine_condition(utils::read.csv(file = "this file does not exist.csv"))                  
# List of 2
# $ message: chr "cannot open the connection"
# $ call   : language file(file, "rt")
# - attr(*, "class")= chr [1:3] "simpleError" "error" "condition"

examine_condition(stop("my error"))
# List of 2
# $ message: chr "my error"
# $ call   : language doTryCatch(return(expr), name, parentenv, handler)
# - attr(*, "class")= chr [1:3] "simpleError" "error" "condition"

library(data.table)
data <- as.data.frame(mtcars)
examine_condition(data[, new_col := 99])  #  ":=" is data.table syntax!
# List of 2
# $ message: chr "Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in pa"| __truncated__
# $ call   : language `:=`(new_col, 99)
# - attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
Run Code Online (Sandbox Code Playgroud)

也可以看看:

gon*_*n90 2

您可以获取错误的类别cnd并检查错误的类型。这里有一个关于下载文件以及如何处理不同错误的小例子:

# Get your items to download
downlodables <- c(paste0('https://www.google.com/', paste0(c('search?q=', '' ), month.name)))

# Iterate over them
for( i in 1:length(downlodables)){

  #Set a 
  dwnl <- tryCatch(download.file(url = downlodables[i], 
                                 destfile = paste0(getwd(),'/', i, '.htm'), 
                                 mode = 'wb'),
                   error = function (e) {e})


  # Check kind of error. Even numbers of 'i'
  class(dwnl) 

  # Check if some error appears
  if (any(class(dwnl) == 'error')){
    # or: any(class(dwnl) %in% c('error', 'warning'))

    # Print your error
    cat(paste0('\n Error found \n', dwnl, '\n'))
    write.csv(cbind(x = i, error = paste0(as.character(dwnl))), file = paste0(i, '.csv'), row.names = FALSE)

    # Conver to string your error
    detailedError <- as.character(dwnl$message) # not necessary

    # Make som in case of denied permisson
    if (any(grep('Permis', detailedError))){
      warning('U shall no pass!')
    }

    # Make som in case of time out conections. In this examlpe try 3 more times the download
    if (any(grep('time', detailedError))){
      count <- 0
      while(count =< 3){

        dwnl <- tryCatch(download.file(url = downlodables[i], 
                                       destfile = paste0(getwd(),'/', i, '.htm'), 
                                       mode = 'wb'),
                         error = function (e) {e})
        if(any(class(dwnl) == 'error')){
          count <- count + 1
        } else { 
          break() 
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)