r - 在多个实例中访问 R 代码块

标签 r try-catch

我有一个代码块,用于在出现特定错误时重试代码执行 3 次。在下面的示例中,如果从 ADLS 容器下载数据期间发生 HTTP 503 错误,我希望执行相同的操作最多重试 3 次。

require(AzureStor)
require(stringr)
recheck <- 0
while (recheck < 3){
  recheck <- recheck + 1
  tryCatch({
    storage_download(container, file, filename, overwrite=TRUE)
    recheck <- 4  
  }, error = function(e){
    if ( sum(str_detect(e, '503')*1) > 0 ){
      print(e)
      print(paste0('An infra-level failure occured. Retry sequence number is : ', recheck))
    } else{
      recheck <<- 4
      print(e)
    }
  }
  )
}

此代码对我来说效果很好,但与上面示例中的 storage_download 类似,我还有其他 ADLS 操作,例如 delete_blobupload_blobstorage_uploadlist_storage_files 在代码中的多个实例中,我必须为每个函数编写上述代码。我想将上面的代码作为一个函数,可以在每个 ADLS 操作期间调用。任何想法或建议都会对我有很大帮助。

最佳答案

以下应该可以解决问题:

with_retries_on_failure = function (expr, retries = 3L) {
    expr = substitute(expr)

    for (try in seq_len(retries)) {
        tryCatch(
            return(eval.parent(expr)),
            error = \(e) {
                if (str_detect(conditionMessage(e), '503')) stop(e)
                message('An infra-level failure occurred. Retry sequence number is: ', try)
            }
        )
    }
}

使用如下:

with_retries_on_failure(storage_download(container, file, filename, overwrite=TRUE))

请注意 return() 调用,它会立即从周围函数返回,而不需要更新循环变量。同样,在失败的情况下,我们也不必更新循环变量,因为我们使用的是 for 循环,并且我们使用 stop() 对于任何非 503 HTTP 响应的错误跳出循环。

关于r - 在多个实例中访问 R 代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75144216/

相关文章:

java - 对于两个整数用户输入,如何检测第一个输入是否传递了字符串?

java - 为什么java.lang.AutoCloseable 的close 方法抛出Exception,而java.io.Closeable 的close 方法抛出IOException?

php - try{...}catch 在 PHP/Symfony2/PHPImap 中不会引发异常

r - 面板数据模型: Duplicate couples error when there are no duplicate couples

r - 将带有逗号的字符串转换为 R 中的向量

使用 R 自动运行超过 30 个特定 set.seed 的回归模型

java - 异常(exception)——为什么还要抛出异常呢?

matlab - MATLAB : Getting error message while using try/catch

删除每个 ID 的重复项

r - 在 R 中选择每组的第二个观察值