Skip to content

Instantly share code, notes, and snippets.

@sckott
Created October 31, 2024 16:24
Show Gist options
  • Save sckott/4d220f06cead8dc8a4d8ee2dbce5546a to your computer and use it in GitHub Desktop.
Save sckott/4d220f06cead8dc8a4d8ee2dbce5546a to your computer and use it in GitHub Desktop.
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(...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment