Zhuzhing custom error messages with {cli}

Nov 13, 2025

Error messages can be cool 😎🤔

IMHO…

Error messages can be cool 😎🤔

…writing assertions is a pain!

The {cli}1 package contains some helpful tools to make your error messages:

  • nicer-looking
  • more helpful
  • more fun to write???

A simple assertion function ☑️❎

check_string <- function(x) {
  stopifnot(rlang::is_string(x))
}

check_string(NA)
Error in check_string(NA): rlang::is_string(x) is not TRUE

We might want to return x if it’s OK

check_string <- function(x) {
  stopifnot(rlang::is_string(x))
  x
}
check_string("A")
[1] "A"

Bringing the zhuzh 💅🏻⏭️

{cli} gives us

For example, we can mark up a span of text as

  • a function name using the .fn class
  • an argument name using the .arg class…

In my error era 🎤✨

What this looks like

check_string <- function(x) {
  cs <- "check_string"
  if (rlang::is_string(x)) {
    x
  } else {
    cli::cli_abort("{.fn {cs}}: argument {.arg x} is not a valid string")
  }
}
check_string(NA)
Error in `check_string()`:
! `check_string()`: argument `x` is not a valid string

The errors tour continues 🏟️💃🏻

check_string <- function(x) {
  cs <- "check_string"
  error_text <- "{.fn {cs}}: argument {.arg x} is not a valid string"
  if (rlang::is_string(x)) {
    x
  } else {
    cli::cli_abort(c(error_text, "x" = "You supplied {.code {x}}"))
  }
}
check_string(NA)
Error in `check_string()`:
! `check_string()`: argument `x` is not a valid string
✖ You supplied `NA`

Nested checking functions 🪆

check_string <- function(x) {
  error_text <- c(
    "{.fn check_string}: argument {.arg x} is not a valid string",
    "x" = "You supplied {.code {x}}"
  )
  if (rlang::is_string(x)) {
    x
  } else {
    cli::cli_abort(error_text, call = rlang::caller_call())
  }
}

my_lower <- \(x) tolower(check_string(x))
my_lower(NA)
Error in `my_lower()`:
! `check_string()`: argument `x` is not a valid string
✖ You supplied `NA`

Summary

  • Take control of the error messages your users might see
  • Let your users know you’ve thought about them?
  • Help yourself have a tiny bit more fun writing input checking code??
  • Help yourself with writing tests and debugging your code

Thank you

and have fun!