Function with multiple warnings
fun_w_multiple_warnings <- function() {
log(-1)
log(-1)
warning("one more")
TRUE
}
fun_w_multiple_warnings()
#> Warning in log(-1): NaNs produced
#> Warning in log(-1): NaNs produced
#> Warning in fun_w_multiple_warnings(): one more
#> [1] TRUE
Function that caputures warnings in a global data frame
caputure_warnings <- function(expr) {
env <- environment()
env$warn <- NULL
value <- withCallingHandlers(
expr,
warning = function(w) {
w_tbl <- tibble::tibble(call = deparse(w$call), warning = w$message)
env$warn <- dplyr::bind_rows(env$warn, w_tbl)
warning(w) # do the same as without caputure_warnings()
invokeRestart("muffleWarning")
}
)
.warnings <<- env$warn
value
}
Wrapping function in caputure_warnings()
caputure_warnings(fun_w_multiple_warnings())
#> Warning in log(-1): NaNs produced
#> Warning in log(-1): NaNs produced
#> Warning in fun_w_multiple_warnings(): one more
#> [1] TRUE
Leaves a global object with warnings
.warnings
#> # A tibble: 3 × 2
#> call warning
#> <chr> <chr>
#> 1 log(-1) NaNs produced
#> 2 log(-1) NaNs produced
#> 3 fun_w_multiple_warnings() one more