mzm
mzm

Reputation: 383

R Log warnings and continue execution

I have a block of R code that is wrapped in a tryCatch statement. Any of the lines in that block can potentially throw a warning or an error. When caught, I have handlers for both warnings and errors, which perform logging in both cases, and exit handling in the error case.

But in the warning case, I just want the warning to be logged, and the execution to continue as normal. At the moment, when warning is caught, it is logged, but the execution is also stopped. Is there an easy way to allow for this functionality?

Upvotes: 6

Views: 1944

Answers (1)

hangler
hangler

Reputation: 400

Not sure if it's the most idiomatic solution, but using a combination of tryCatch and withCallingHandlers works for me in an almost identical situation.

I wrap the call to my function with withCallingHandlers, providing a function to handle warnings; execution of the function will continue afterwards. I wrap all of that in tryCatch, providing a function to handle errors.

tryCatch(
    withCallingHandlers(doSomething(), warning = function(w) logWarning(w)),
    error = function(e) logError(e)
)

Thanks to nicola in the comments for the withCallingHandlers tip.

Upvotes: 3

Related Questions