我有一个代码块,用于在出现特定错误时重试代码执行 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_blob
、upload_blob
、 storage_upload
、list_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/