[R] How to catch both warnings and errors?

Marius Hofert m_hofert at web.de
Sun Dec 5 21:13:47 CET 2010


Dear expeRts,

I am struggling with warning/error handling. 

I would like to call a function which can produce either 
a) normal output
b) a warning
c) an error

Since the function is called several (thousand) times in a loop, I would like 
to proceed "quietly" and collect the warnings and errors [to deal with them at a
later point]. 

I have seen constructs with tryCatch (which can deal with errors) and with
withCallingHandlers (which can deal with warnings), but I cannot figure out how
to catch *both* warnings and errors. Below is a minimal example of the function 
that is called several times in a large loop. The function should catch warnings 
and errors; the former work fine, but with the latter I do not know how to proceed.

The function should *always* return the list with the three components.

How can I achieve this?

Cheers,

Marius

Ps: How can I get the warning/error message in a nice string (as it is printed
in a normal warning/error message)? The approach shown below is somehow ugly. 
Basically, I had trouble converting the call w$call to a string.

## based on http://tolstoy.newcastle.edu.au/R/help/04/06/0217.html
## and http://www.mail-archive.com/r-help@r-project.org/msg81380.html
f <- function(x){
    ## warnings
    w.list <- NULL # init warning
    w.handler <- function(w){ # warning handler
	warn <- simpleWarning(w$message, w$call) # build warning
        w.list <<- c(w.list, paste(warn, collapse = " ")) # save warning
        invokeRestart("muffleWarning")
    }
    ## errors
    e.list <- NULL # init errors
    e.handler <- function(e){ # error handler
	err <- simpleError(e$message, e$call)
	e.list <<- c(e.list, paste(err, collapse = " ")) # save error 
    }
    ## execute command   
    res <- withCallingHandlers(log(x), warning = w.handler, error = e.handler)
    ## return result with warnings and errors
    list(result = res, warning = w.list, error = e.list)
}

f(1) 
f(-1) 
f("a")



More information about the R-help mailing list