Skip to content

Use cli to give detailed, friendly error messages #206

@capnrefsmmat

Description

@capnrefsmmat

There are a few functions that call stop() to signal invalid inputs or other user errors. We should use cli_abort() for these. It allows you to give detail on the types of arguments and what was expected, in a much friendlier way than just pasting together a message in stop().

Here are a couple examples from a package of mine:

  if (!inherits(population, "population")) {
    cli_abort(c("{.arg population} argument must be a population defined with {.fn population}",
                "i" = "Received {.type {population}} instead"))
  }
    cli_abort(
      c("Diagnostic function {.arg fn} must return a data frame or tibble",
        "x" = "{.arg fn} returned a result of class {.cls {class(x)}}"),
      class = "regressinator_diagnostic_class",
      call = caller_env()
    )

These get pretty-printed with colored formatting, and the markup like {.cls} produces nice formatting. For instance, here's what you get from the second example:

Error in `sampling_distribution()`:
! diagnostic function `fn` must return a data frame or tibble
✖ `fn` returned a result of class <character>
Run `rlang::last_trace()` to see where the error occurred.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions