Skip to content

Instantly share code, notes, and snippets.

@maurolepore
Created August 27, 2021 19:59
Show Gist options
  • Save maurolepore/96d9231df77758b6e84bffb9f438cbd0 to your computer and use it in GitHub Desktop.
Save maurolepore/96d9231df77758b6e84bffb9f438cbd0 to your computer and use it in GitHub Desktop.
# A custom error with base
f <- function() {
  message <- paste(c("Oh no", "Messed up", "Need a hint?"), collapse = "\n")
  # Construct a custom class via `errorCondition()`
  stop(errorCondition(message, class = "my_error"))
}

# How it prints
f()
#> Error: Oh no
#> Messed up
#> Need a hint?

# How to test it
testthat::expect_error(tools::assertError(f(), classes = "my_error"), NA)



# A custom error with rlang
f <- function() {
  # `x`, `i`, and unnamed bullets print nicely via `rlang::format_error_bullets()`
  message <- c("Oh no", x = "Messed up", i = "Need a hint?")
  # Construct a custom class direcly via `rlang::abort()`
  rlang::abort(message, class = "my_error")
}

# How it prints
f()
#> Error: Oh no
#> x Messed up
#> ℹ Need a hint?

# How to test it
testthat::expect_error(f(), class = "my_error")

Created on 2021-08-27 by the reprex package (v2.0.1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment