Create custom error messages

Is it possible to overwrite any function to customize the default error messages of R?

Hi @aguerodev. You may use tryCatch as the following link.
http://www.win-vector.com/blog/2012/10/error-handling-in-r/

The idea is to be able to overwrite the error messages to make them more friendly for my students.

One thing you can try is "monkey patching," where you create a new function with the same name. This is pretty easy in R. For your case, the new function would wrap a tryCatch around a call to the original function, look for certain error messages, and raise custom errors when it sees them.

For example, these lm error messages aren't helpful for new users:

lm(goblins ~ pirates, data = mtcars)
# Error in eval(predvars, data, env) : object 'goblins' not found
lm(BJsales)
# Error in formula.default(object, env = baseenv()) : invalid formula

A replacement with better messages:

new_lm <- function(...) {
  # Record the parameter values as written
  data_text <- deparse(substitute(data))
  formula_text <- deparse(substitute(formula))
  tryCatch(
    # Use :: notation to make sure we use the original version
    stats::lm(formula = formula, data = data, ...),
    error = function(err) {
      msg <- conditionMessage(err)
      if (grepl("object '.*' not found", msg)) {
        new_msg <- gsub(
          "object ('.*') not found",
          paste("\\1 is not in", data_text),
          msg
        )
        stop(new_msg)
      }
      if (grepl("invalid formula", msg)) {
        new_msg <- paste0(
          "'", formula_text, "' is not a valid formula.\n",
          "See ?lm or ?formula for help."
        )
        stop(new_msg)
      }
      stop(err)
    }
  )
}

# Give it named parameters instead of just "..."
# These are helpful with most IDEs
formals(new_lm) <- formals(lm)
lm <- new_lm

lm(goblins ~ pirates, data = mtcars)
# Error in value[[3L]](cond) : 'goblins' is not in mtcars
lm(BJsales)
# Error in value[[3L]](cond) : 'BJsales' is not a valid formula.
# See ?lm or ?formula for help.

You can put your monkey-patch functions in a package for the students.


For those who want to make this more automated, I tried putting the deparse(substitute(x)) inside a loop over all parameters. But environments are wonky. If anyone can do this, I'd like to see the solution. If anyone can do this elegantly, I'd love to see the solution.

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.