Skip to content
Prev 243983 / 398506 Next

How to catch both warnings and errors?

On Dec 5, 2010, at 3:13 PM, Marius Hofert wrote:

            
I do not see the function warnings() being used below:

?warnings

It delivers the stored warnings with different default behavior for  
interactive and non-interactive sessions.
Made some changes in you code but don't know if it is what you were  
hoping for:

f <- function(x){
    ## warnings
    w.list <- NULL # init warning
    w.handler <- function(w){ # warning handler
	    warn <- simpleWarning(w$message, w$call) # build warning
# first change here
        w.list <<- c(w.list, paste(warnings(), collapse = " ")) # save  
warning
        invokeRestart("muffleWarning")
        }
    ## errors
      e.list <- NULL # init errors   # not sure this is  good idea
      e.handler <- function(e){ # error handler
	     err <- c(e.list, e$message, e$call) # save error
	     return( err)
         }
    ## execute command
# wrapped cal in try()
    res <- withCallingHandlers(try(log(x)), warning = w.handler, error  
= e.handler)
    ## return result with warnings and errors
    list(result = res, warning = w.list, error = e.list)
}
David Winsemius, MD
West Hartford, CT