Skip to content

Instantly share code, notes, and snippets.

@christophsax
Created November 19, 2021 17:54
Show Gist options
  • Save christophsax/85ac695ea02a7b7309448bc6e1feda78 to your computer and use it in GitHub Desktop.
Save christophsax/85ac695ea02a7b7309448bc6e1feda78 to your computer and use it in GitHub Desktop.
Collecting warnings in a data frame

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment