Including function calls in error messages — topic-error-call
Starting with rlang 1.0, abort() includes the erroring function in the message by default:
my_function <- function() {
abort("Can't do that.")
}
my_function()
#> Error in `my_function()`:
#> ! Can't do that.
This works well when abort() is called directly within the failing function. However, when the abort() call is exported to another function (which we call an "error helper"), we need to be explicit about which function abort() is throwing an error for.
This works well when abort() is called directly within the failing function. However, when the abort() call is exported to another function (which we call an "error helper"), we need to be explicit about which function abort() is throwing an error for.
There are two main kinds of error helpers:
Simple abort() wrappers. These often aim at adding classes and attributes to an error condition in a structured way:
stop_my_class <- function(message) {
abort(message, class = "my_class")
}
Input checking functions. An input checker is typically passed an input and an argument name. It throws an error if the input doesn't conform to expectations:
check_string <- function(x, arg = "x") {
if (!is_string(x)) {
cli::cli_abort("{.arg {arg}} must be a string.")
}
}
To fix this, let abort() know about the function that it is throwing the error for by passing the corresponding function environment as the call argument: