Catch a special warning and ignore others

I am debugging code that gives several warnings, but I am trying to stop the code when I get a specific warning so that I can look at the environment.

For instance:

myfun <- function(){ warning("The wrong warning") warning("The right warning") print("The end of the function") } tryCatch(myfun(), warning = function(w){ if(grepl("right", w$message)){ stop("I have you now") } else { message(w$message) } }) 

I would like the function to stop at the “Correct Warning”, but the trick stops as soon as it receives its first warning. How can I skip warnings that are of no interest and stop at those that interest me?

+5
source share
1 answer

I believe withCallingHandlers is what you want: Apart from the simple warnings / errors in tryCatch ()

 withCallingHandlers(myfun(), warning = function(w){ if(grepl("right", w$message)){ stop("I have you now") } else { message(w$message) } }) 
+3
source

All Articles