Evaluates an expression while also capturing error and warning conditions.
Function always returns a named list list(result=, warning=, error=)
.
If there are no errors or warnings, those elements will be NULL
.
If there is an error, the result element will be NULL
.
Messages are neither saved nor printed to the console.
Evaluation is done via rlang::eval_tidy()
. If errors and warnings are produced
using the {cli}
package, the messages are processed with cli::ansi_strip()
to remove styling from the message.
captured_condition_as_message()
/captured_condition_as_error()
These functions take the result from eval_capture_conditions()
and return
errors or warnings as either messages (via cli::cli_inform()
) or
errors (via cli::cli_abort()
). These functions handle cases where the
condition messages may include curly brackets, which would typically cause
issues when processed with the cli::cli_*()
functions.
Functions return the "result"
from eval_capture_conditions()
.
eval_capture_conditions(expr, data = NULL, env = caller_env())captured_condition_as_message(
x,
message = c("The following {type} occured:", x = "{condition}"),
type = c("error", "warning"),
envir = rlang::current_env()
)
captured_condition_as_error(
x,
message = c("The following {type} occured:", x = "{condition}"),
type = c("error", "warning"),
call = get_cli_abort_call(),
envir = rlang::current_env()
)
a named list
An expression or quosure to evaluate.
A data frame, or named list or vector. Alternatively, a
data mask created with as_data_mask()
or
new_data_mask()
. Objects in data
have priority over those in
env
. See the section about data masking.
The environment in which to evaluate expr
. This
environment is not applicable for quosures because they have
their own environments.
(captured_condition
)
a captured condition created by eval_capture_conditions()
.
(character
)
message passed to cli::cli_inform()
or cli::cli_abort()
. The condition
being printed is saved in an object named condition
, which should be
included in this message surrounded by curly brackets.
(string
)
the type of condition to return. Must be one of 'error'
or 'warning'
.
Environment to evaluate the glue expressions in.
(environment
)
Execution environment of currently running function. Default is
get_cli_abort_call()
.
# function executes without error or warning
eval_capture_conditions(letters[1:2])
# an error is thrown
res <- eval_capture_conditions(stop("Example Error!"))
res
captured_condition_as_message(res)
# if more than one warning is returned, all are saved
eval_capture_conditions({
warning("Warning 1")
warning("Warning 2")
letters[1:2]
})
# messages are not printed to the console
eval_capture_conditions({
message("A message!")
letters[1:2]
})
Run the code above in your browser using DataLab