I am dealing with a function that is throwing both errors and warnings. (related: A Warning About Warning )
Often, a warning will proceed an error. In thes
I would write a function that executes an expression and prioritizes the errors.
prioritize.errors <- local({
# this function executes an expression and stores the warnings
# until it finishes executing.
warnings <- list()
w.handler <- function(w) {
warnings <<- c(warnings, list(w))
invokeRestart('muffleWarning') # here's the trick
}
function(expr) {
withCallingHandlers({expr}, warning=w.handler)
for (w in warnings) warning(w)
warnings <<- list()
}
})
F.warning <- function() {
warning("a warning")
message('ok')
}
test <- function(expr) {
tryCatch(expr,
error=function(e) cat("ERROR CAUGHT"),
warning=function(w) cat("WARNING CAUGHT")
)
}
test(prioritize.errors(F.error()))
# ERROR CAUGHT
test(prioritize.errors(F.warning()))
# ok
# WARNING CAUGHT
test(prioritize.errors(F.errorAndWarning()))
# I have moved on.ERROR CAUGHT