Run a block of code, collecting any deferrable_error calls that occur. Ordinary errors will be thrown immediately.

defer_errors(expr, handler = stop)

Arguments

expr

An expression to evaluate

handler

The final handler for the deferred errors. The default is stop which will raise the collected error. Alternatively, use return to return the error

Details

The error object will contain an element errors with the deferred errors, each of which will contain elements message, call (the call that precedes deferrable_error and calls which contains the "interesting" part of the stack trace (i.e., only calls below the defer_errors infrastructure).

Examples

check_positive <- function(x) { if (x < 0) { deferrable_error(paste("got a negative number:", x)) } } err <- tryCatch( defer::defer_errors({ check_positive(0) check_positive(-1) check_positive(-2) }), error = identity) err
#> <deferred_errors: 2 errors occured: #> - got a negative number: -1 #> - got a negative number: -2>
# Directly return the error: err <- defer::defer_errors({ check_positive(0) check_positive(-1) check_positive(-2) }, handler = return) # Stack traces are included to improve downstream reporting: f <- function(x) { g(x) } g <- function(x) { check_positive(x) } err <- defer_errors({ f(0) f(-1) f(-2) }, handler = return) err$errors[[1]]$calls
#> [[1]] #> f(-1) #> #> [[2]] #> g(x) #> #> [[3]] #> check_positive(x) #> #> [[4]] #> deferrable_error(paste("got a negative number:", x)) #>