tryCatch in R: how do I capture all warning messages in the function passed to the warning parameter?

some_f <- function() {
  warning("warning 1")
  warning("warning 2")
}

tryCatch(some_f(),
         warning=function(warn) warn)

Output:

<simpleWarning in some_f(): warning 1>

I need to be able to capture both of the warnings in the function that I pass to the "warning" parameter.

Upvotes: 2

Views: 443

Answers (1)

J.P. Le Cavalier
J.P. Le Cavalier

Reputation: 1345

This is a minimal example to catch multiple warnings resulting from your f() function:

warns <- list()
withCallingHandlers(some_f(), warning = function(warn) {warns <<- append(warns, warn)})
warns

##  $message
##  [1] "warning 1"
##  
##  $call
##  some_f()
##  
##  $message
##  [1] "warning 2"
##  
##  $call
##  some_f()

Upvotes: 1

Related Questions