8

I'm debugging some code which gives several warnings, but I'm trying to stop the code when I receive a specific warning so I can look at the environment.

For example:

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)
           }
         })

What I'd like to happen is for the function to stop at "The right warning", but the catch stops as soon as it receives its first warning. How can I skip over warnings that aren't of interest and stop on the ones that interest me?

sebastian-c
  • 15,057
  • 3
  • 47
  • 93

1 Answers1

5

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

withCallingHandlers(myfun(),
   warning = function(w){
     if(grepl("right", w$message)){
       stop("I have you now")
     } else {
       message(w$message)
     }
   })
Community
  • 1
  • 1
fanli
  • 1,069
  • 7
  • 13