Last active
August 3, 2023 12:57
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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