Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to overwrite base R error messages?

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"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading