with_abort() promotes all errors as if they were thrown with abort(). These errors embed a backtrace. They are particularly suitable to be set as parent errors (see parent argument of abort()).

with_abort(expr)

Arguments

expr

An expression run in a context where errors are promoted to rlang errors.

Details

with_abort() installs a calling handler for errors and rethrows non-rlang errors with abort(). However, error handlers installed within with_abort() have priority. For this reason, you should use tryCatch() and exiting handlers outside with_abort() rather than inside.

Examples

# For cleaner backtraces: options(rlang_trace_top_env = current_env()) # with_abort() automatically casts simple errors thrown by stop() # to rlang errors: fn <- function() stop("Base error") try(with_abort(fn())) last_error()
#> <error> #> message: Base error #> class: `rlang_error` #> backtrace: #> ─global::fn() #> ─base::stop("Base error") #> Call `summary(rlang::last_error())` to see the full backtrace
# with_abort() is handy for rethrowing low level errors. The # backtraces are then segmented between the low level and high # level contexts. low_level1 <- function() low_level2() low_level2 <- function() stop("Low level error") high_level <- function() { with_handlers( with_abort(low_level1()), error = ~ abort("High level error", parent = .x) ) } try(high_level()) last_error()
#> <error> #> message: High level error #> class: `rlang_error` #> backtrace: #> ─base::try(high_level()) #> ─global::high_level() #> <error: parent> #> message: Low level error #> class: `rlang_error` #> backtrace: #> ─rlang::with_abort(low_level1()) #> ─global::low_level1() #> ─global::low_level2() #> ─base::stop("Low level error") #> Call `summary(rlang::last_error())` to see the full backtrace
#> <error> #> message: High level error #> class: `rlang_error` #> fields: `message`, `trace` and `parent` #> backtrace: #> █ #> ├─base::try(high_level()) #> │ └─base::tryCatch(...) #> │ └─base:::tryCatchList(expr, classes, parentenv, handlers) #> │ └─base:::tryCatchOne(expr, names, parentenv, handlers[[1L]]) #> │ └─base:::doTryCatch(return(expr), name, parentenv, handler) #> └─global::high_level() #> <error: parent> #> message: Low level error #> class: `rlang_error` #> fields: `message`, `trace`, `parent` and `error` #> backtrace: #> █ #> ├─rlang::with_abort(low_level1()) #> │ └─base::withCallingHandlers(...) /home/travis/build/r-lib/rlang/R/cnd.R:857:2 #> └─global::low_level1() #> └─global::low_level2() #> └─base::stop("Low level error")
# Reset to default options(rlang_trace_top_env = NULL)