Skip to content

Instantly share code, notes, and snippets.

@mitchelloharawild
Created August 9, 2019 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitchelloharawild/b4a0a5c03c1a907f82685a186e0e6fc3 to your computer and use it in GitHub Desktop.
Save mitchelloharawild/b4a0a5c03c1a907f82685a186e0e6fc3 to your computer and use it in GitHub Desktop.
Capture results, messages, warnings and errors into a list
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