Skip to content

Instantly share code, notes, and snippets.

@mihaiconstantin
Last active August 3, 2023 12:57
Show Gist options
  • Save mihaiconstantin/c4260fb8d7f3cd37e37bad589db4c270 to your computer and use it in GitHub Desktop.
Save mihaiconstantin/c4260fb8d7f3cd37e37bad589db4c270 to your computer and use it in GitHub Desktop.
Stop `R` warnings from printing and capture them in a variable for later handling.
# Please run the code top to bottom and follow the comments.
# Task function with errors or warnings.
naughty_task <- function(error = TRUE, warning = FALSE) {
# If warning.
if (warning) {
warning("Warning thrown.")
}
# If error.
if (error) {
stop("Error thrown.")
}
}
# Test the function.
naughty_task(error = TRUE, warning = TRUE)
# Collect errors and warnings.
errors <- NULL
warnings <- NULL
# Try to run.
tryCatch(withCallingHandlers(
# The expression to evaluate.
expr = naughty_task(error = TRUE, warning = TRUE),
# The warning handler.
warning = function(w) {
# Store warning.
warnings <<- c(warnings, w$message)
# Prevent the warning from being printed.
invokeRestart("muffleWarning")
}),
# The error handler.
error = function(e) {
# Store error.
errors <<- c(errors, e$message)
}
)
# Check the collectors.
errors
warnings
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment