Skip to content

How to catch both warnings and errors?

1 message · Samuel Meyer

#
I tried to use this solution (from over two years ago, but it remains an official demo), but found that it only captured the last warning rather than all of them. Instead, the code below collects all warnings.

tryCatch.W.E <- function(expr)
{
    W <- list()
    w.handler <- function(w){ # warning handler
	W <<- c(W,list(w))
	invokeRestart("muffleWarning")
    }
    list(value = withCallingHandlers(tryCatch(expr, error = function(e) e),
				     warning = w.handler),
	 warning = W)
}
Sam Meyer