Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Log warnings and continue execution

Tags:

r

try-catch

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?

like image 462
mzm Avatar asked Jun 15 '16 13:06

mzm


1 Answers

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.

like image 169
hangler Avatar answered Sep 29 '22 15:09

hangler