Turn errors from an expression into a dataexcept error¶
Source: R/groups.R ยท Help: ?wrap_errors
wrap_errors() evaluates expr, and if it signals an error, signals the
error constructor builds instead, with the original as its cause. It is
the R counterpart of the Python package's wrap() and wrapping(), and
replaces the handler that is otherwise written out by hand:
Usage¶
Arguments¶
expr- The expression to evaluate.
constructor- A function returning a condition, called with
...andparent, the condition that was caught: any dataexcept constructor, or your own. ...- Arguments for
constructor. on- The classes of condition to wrap. The default wraps errors only;
c("error", "warning")also turns a warning into the wrapped error, which suits functions such asread.csv()that warn before they fail. failure- Failure metadata for the new error, from
failure_metadata(), orNULLfor the constructor's default.
Value¶
The value of expr, when nothing is wrapped.
Details¶
The original condition is always recorded as the cause, so it stays in the
envelope and in rlang's "Caused by" output. Conditions other than those in
on pass through untouched, as do interrupts.
Examples¶
path <- tempfile(fileext = ".csv")
err <- tryCatch(
wrap_errors(read.csv(path), file_read_error, path = path, on = c("error", "warning")),
dataexcept_file_error = identity
)
conditionMessage(err)
class(err$parent)
# A transient failure, as far as the caller knows.
fetch <- function() stop("connection reset by peer")
err <- tryCatch(
wrap_errors(fetch(), api_error,
endpoint = "https://api.example.com/v1/rates",
failure = failure_metadata("transient", retryable = TRUE)
),
dataexcept_error = identity
)
is_retryable(err)