Skip to content
Prev 243988 / 398506 Next

How to catch both warnings and errors?

On Dec 5, 2010, at 7:35 PM, Marius Hofert wrote:

            
Sorry. I was being misled by warnings that existed at my global level  
into thinking i had succeeded. This modification will suppress warning  
and error but will not populate the lists as we had hoped:

f <- function(expr){
  ## warnings
  w.list <- NULL # init warning
  w.handler <- function(w){ # warning handler
	    warn <- c(w$message, w$call) # build warning
# first change here
      muffleWarning <<- c(w.list, warn, collapse = " ") # save warning
           invokeRestart("muffleWarning")}
  ## errors
    e.list <- NULL # init errors   # not sure this is  good idea
    e.handler <- function(e){ # error handler
	     e.list <<- c(e.list, e$message, e$call) # save error
	     return( e.list)
       }
  ## execute command
# wrapped cal in try()
  res <- withCallingHandlers(try(expr, silent=TRUE), warning =  
w.handler, error = e.handler)
  ## return result with warnings and errors
   list(result = res, warning = w.list, error = e.list)
}

 > test <- f(log(-1))
 > test
$result
[1] NaN

$warning
NULL

$error
NULL

 > test <- f(log("a"))
 > test
$result
[1] "Error in log(\"a\") : Non-numeric argument to mathematical  
function\n"
attr(,"class")
[1] "try-error"

$warning
NULL

$error
NULL
David Winsemius, MD
West Hartford, CT