Created
August 9, 2019 03:40
-
-
Save mitchelloharawild/b4a0a5c03c1a907f82685a186e0e6fc3 to your computer and use it in GitHub Desktop.
Capture results, messages, warnings and errors into a list
This file contains hidden or 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
so_many_problems <- function(){ | |
message("msg") | |
message("msg2") | |
warning("warn") | |
warning("warn2") | |
warning("warn3") | |
if(runif(1) > 0.5){ | |
stop("error") | |
} | |
"yay" | |
} | |
capture_all_problems <- function(expr){ | |
msg <- list() | |
wrn <- list() | |
err <- NULL | |
withCallingHandlers( | |
result <- tryCatch( | |
expr, | |
error = function(e){ | |
err <<- e$message | |
NULL | |
} | |
), | |
message = function(m){ | |
msg[[length(msg) + 1]] <<- m$message | |
invokeRestart("muffleMessage") | |
}, | |
warning = function(w){ | |
wrn[[length(wrn) + 1]] <<- w$message | |
ops <- options(warn = -1) | |
on.exit(options(ops)) | |
invokeRestart("muffleWarning") | |
} | |
) | |
list( | |
result = result, | |
message = msg, | |
warning = wrn, | |
error = err | |
) | |
} | |
capture_all_problems(so_many_problems()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment