Skip to contents

The function is used as a fail-safe if your R code sometimes works and sometimes doesn't, usually because it depends on a resource that may be temporarily unavailable. It tries to evaluate the expression `max_tries` times. If all the attempts fail, it throws an error; if not, the evaluated expression is returned.

Usage

try_get(expr, max_tries = 5, error_message = "", retry_message = "Retrying...")

Arguments

expr

The expression to be evaluated.

max_tries

The maximum number of attempts to evaluate the expression before giving up. Default is set to 5.

error_message

a string, additional custom error message you would like to be displayed when an error occurs.

retry_message

a string, a message displayed when a new try to evaluate the expression would be attempted.

Value

This function returns the evaluated expression if successful, otherwise it throws an error if all attempts are unsuccessful.

Examples

f <- function() {
  value <- runif(1, min = 0, max = 1)
  if (value > 0.5) {
    log_message("value is larger than 0.5")
    return(value)
  } else {
    log_message(
      "value is smaller than 0.5",
      message_type = "error"
    )
  }
}
f_evaluated <- try_get(expr = f())
#>  [2025-07-03 09:02:39] Error in log_message("value is larger than 0.5"): could not find function "log_message"
#>  [2025-07-03 09:02:39] 
#>  [2025-07-03 09:02:39] 
#>  [2025-07-03 09:02:40] Retrying...
#>  [2025-07-03 09:02:40] Error in log_message("value is larger than 0.5"): could not find function "log_message"
#>  [2025-07-03 09:02:40] 
#>  [2025-07-03 09:02:40] 
#>  [2025-07-03 09:02:41] Retrying...
#>  [2025-07-03 09:02:41] Error in log_message("value is larger than 0.5"): could not find function "log_message"
#>  [2025-07-03 09:02:41] 
#>  [2025-07-03 09:02:41] 
#>  [2025-07-03 09:02:42] Retrying...
#>  [2025-07-03 09:02:42] Error in log_message("value is smaller than 0.5", message_type = "error"): could not find function "log_message"
#>  [2025-07-03 09:02:42] 
#>  [2025-07-03 09:02:42] 
#>  [2025-07-03 09:02:43] Retrying...
#>  [2025-07-03 09:02:43] Error in log_message("value is larger than 0.5"): could not find function "log_message"
#>  [2025-07-03 09:02:43] 
#>  [2025-07-03 09:02:43] 
#> Error: Error in log_message("value is larger than 0.5"): could not find function "log_message"
print(f_evaluated)
#> Error in h(simpleError(msg, call)): error in evaluating the argument 'x' in selecting a method for function 'print': object 'f_evaluated' not found