library(cli)
library(rlang)
assert1 <- function(x, y, arg = caller_arg(x)) {
if (!inherits(x, y)) {
abort(format_error("{.strong {arg}} must be of class {y}"))
}
}
assert2 <- function(x, y, arg = caller_arg(x), call = caller_env()) {
if (!inherits(x, y)) {
abort(format_error("{.strong {arg}} must be of class {y}"), call = call)
}
}
some_fun1 <- function(x, class) {
assert1(x, class)
}
some_fun2 <- function(x, class) {
assert2(x, class)
}
some_fun1(5, "character")
#> Error in `assert1()`:
#> ! x must be of class character
last_trace()
#> <error/rlang_error>
#> Error in `assert1()`:
#> ! x must be of class character
#> ---
#> Backtrace:
#> ▆
#> 1. └─global some_fun1(5, \"character\")
#> 2. └─global assert1(x, class)
#> Run rlang::last_trace(drop = FALSE) to see 1 hidden frame.
some_fun2(5, "character")
#> Error in `some_fun2()`:
#> ! x must be of class character
last_trace()
#> <error/rlang_error>
#> Error in `some_fun2()`:
#> ! x must be of class character
#> ---
#> Backtrace:
#> ▆
#> 1. └─global some_fun2(5, \"character\")
#> Run rlang::last_trace(drop = FALSE) to see 2 hidden frames.
# we have to run last_trace(drop = FALSE) to see the actual
# function the error occurred in
last_trace(drop = FALSE)
#> <error/rlang_error>
#> Error in `some_fun2()`:
#> ! x must be of class character
#> ---
#> Backtrace:
#> ▆
#> 1. └─global some_fun2(5, \"character\")
#> 2. └─global assert2(x, class)
#> 3. └─rlang::abort(...)