Home > Enterprise >  Is it possible to overwrite base R error messages?
Is it possible to overwrite base R error messages?

Time:05-31

I would like to overwrite a not very helpful error message from a base R function and replace it with a custom error message. How could I achieve this?

To clarify, assume that I evaluate the following expression "a" "b". Because I am trying to add two characters, R will complain and return "Error in "a" "b" : non-numeric argument to binary operator".

Is there a way to catch this exact error message, and return a clearer error message, e.g. "You are trying to add two factors - this is not allowed"?

I suppose a starting point would be to work with the try function and grepl:

a <- try("a"   "a", silent = TRUE)

if(inherits(a, "try-error")){
  cond <- sum(grepl("non-numeric argument to binary operator", deparse(a), fixed = TRUE)) > 0
  if(cond){
    stop("You are trying to add two characters. This is not allowed.")
  }
}

But maybe there is a more 'generic' or 'elegant' way to do this?

CodePudding user response:

You can check the class with inherits and then use the "condition" attribute as follows using grepl like what you suggest

a <- try("a"   "a", silent = TRUE)
if(inherits(a, "try-error") && grepl("non-numeric argument to binary operator$", attr(a, "condition")$message))
    stop("You are trying to add two non-numbers")
#R> Error: You are trying to add two non-numbers

but many things could cause this error it seem. E.g.

a <- try(list()   list(), silent = TRUE)
if(inherits(a, "try-error") && grepl("non-numeric argument to binary operator$", attr(a, "condition")$message))
    stop("You are trying to add two non-numbers")
#R> Error: You are trying to add two non-numbers

A better idea may be to check the arguments if possible. E.g. using stopifnot().

  • Related