user3190185
user3190185

Reputation: 63

Logging and writing error messages to a dataframe

I intend to record the errors in my R code while calling functions in a dataframe (ERR_LOG, say). I want to use 'try' to identify errors while calling a function,if any.The dataframe(ERR_LOG) will have the following columns :

  1. Time : The time at which the function was called (Sys.time)
  2. Loc : For which function call was this error recorded (name of the function)
  3. Desc : Description of the error which R throws at us (Error message in R)

Example :

First I would like to initialize a blank dataframe 'ERR_LOG' with these columns

Then write the function

f <- function(a){
  x <- a*100
  return(x)
}

Now I put the output of the call to 'f' in 'chk'

chk <- try(f())

The above call gives the error 'Error in a * 100 : 'a' is missing' (description of the error)

Check

if(inherits(chk,'try-error'))

{then I want to populate ERR_LOG and stop the code execution}

How can this be done in R?

Upvotes: 2

Views: 436

Answers (1)

Ricardo Saporta
Ricardo Saporta

Reputation: 55350

use tryCatch instead of try

Then inside tryCatch(), use the argument error=function(e){}

e will have an element named message, which is what you would like

Use the following call with browser to explore e$message:

x <- tryCatch(stop("This is your error message"), error=function(e) {browser()})

Note that your function need not be anonymous.

MyErrorParser <- function(e) {
  m <- e$message
  if (grepl("something", m))
     do something
  return (something_else)
}

## THEN
tryCatch(stop("This is a test"), error=MyErrorParser)

Upvotes: 1

Related Questions