Skip to content

Instantly share code, notes, and snippets.

@olivroy
Created June 28, 2024 19:23
Show Gist options
  • Save olivroy/38b8c09aa26fd9a1663991fc0d6b1b15 to your computer and use it in GitHub Desktop.
Save olivroy/38b8c09aa26fd9a1663991fc0d6b1b15 to your computer and use it in GitHub Desktop.
Error messagess
f_error <- function(arg, msg, call = rlang::caller_env()) {
if (TRUE) {
# THe naive way
cli::cli_abort(c("{.arg {arg}} is wrong", msg), call = call)
}
}
f_error2 <- function(arg, msg, call = rlang::caller_env(), .envir = parent.frame()) {
if (TRUE) {
# doesn't work since arg needs to evaluate in current frame, but msg should evaluate in parent frame
cli::cli_abort(c("{.arg {arg}} is wrong", msg), call = call, .envir = .envir)
}
}
# works correctly
f_error3 <- function(arg, msg, call = rlang::caller_env(), .envir = parent.frame()) {
if (TRUE) {
# evaluate msg with .envir (parent frame)
msg <- cli::format_message(msg, .envir = .envir)
# evaluate arg in current frame
cli::cli_abort(c("{.arg {arg}} is wrong", msg), call = call)
}
}
# works corrrectly
f_error4 <- function(arg, msg, call = rlang::caller_env(), .envir = parent.frame()) {
if (TRUE) {
cli::cli_abort(c("{.arg {arg}} is wrong"), call = call, footer = cli::format_message(msg, .envir = .envir))
}
}
f_user <- function(f) {
intermediate <- c("x", "y", "z")
f(
"x",
"not {intermediate}"
)
}
# not correct
f_user(f_error)
f_user(f_error2)
# correct
f_user(f_error3)
f_user(f_error4)
# Another way, less elegant
f_user2 <- function(f) {
intermediate <- c("x", "y", "z")
f(
"x",
cli::format_message("not {intermediate}")
)
}
f_user2(f_error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment