R避免“重啟中斷承諾評估”警告
問題
看來,在一個函式內,當您評估一個多次產生錯誤的表示式時,會收到警告重新啟動中斷的承諾評估.例如:
foo <- function() stop("Foo error") bar <- function(x) { try(x) x } bar(foo())
產量
Error in foo() : Foo error Error in foo() : Foo error In addition: Warning message: In bar(foo()) : restarting interrupted promise evaluation
如何避免這種警告並妥善處理?
背景
特別是在寫入資料庫的操作中,可能會遇到需要重試操作幾次的鎖定錯誤.因此,我在tryCatch周圍建立一個包裝,重新計算一個表示式直到n次,直到成功:
tryAgain <- function(expr, n = 3) { success <- T for (i in 1:n) { res <- tryCatch(expr, error = function(e) { print(sprintf("Log error to file: %s", conditionMessage(e))) success <<- F e } ) if (success) break } res }
但是,我正在收到重新啟動中斷的承諾評估訊息的負載:
>tryAgain(foo()) [1] "Log error to file: Foo error" [1] "Log error to file: Foo error" [1] "Log error to file: Foo error" <simpleError in foo(): Foo error> Warning messages: 1: In doTryCatch(return(expr), name, parentenv, handler) : restarting interrupted promise evaluation 2: In doTryCatch(return(expr), name, parentenv, handler) : restarting interrupted promise evaluation
理想情況下,我想完全避免這些資訊,而不是僅僅將其消除,因為我也可能想要處理來自expr的真實警告.