rlang icon indicating copy to clipboard operation
rlang copied to clipboard

`stop_input_type()` needs a little more flexible in the error message for typed anonymous functions

Open hadley opened this issue 1 month ago • 0 comments

In ellmer, I had a credentials callback that should be a zero-argument function that returns a string or a list. I've written this check_ function for it:

check_credentials <- function(credentials, error_call = caller_env()) {
  check_function(credentials, allow_null = TRUE, call = error_call)
  if (length(formals(credentials)) != 0) {
    cli::cli_abort(
      "{.arg credentials} must not have arguments.",
      call = error_call
    )
  }

  creds <- credentials()
  if (!is_string(creds) && !(is_named(creds) && is.list(creds))) {
    stop_input_type(
      creds,
      c("a string", "a named list"),
      call = error_call,
      arg = "credentials()"
    )
  }

  invisible()
}

The problem is this case:

check_credentials(\() 1)
#> Error:
#> ! `credentials()` must be a string or a named list, not the number 1.

Here it's a bit easy to miss that the constraint is on the return value of the function, not the function itself. It would be nice it we could make that a little more clear, maybe like this?

check_credentials(\() 1)
#> Error:
#> ! `credentials()` must return a string or a named list, not the number 1.

hadley avatar Nov 03 '25 14:11 hadley