Exercise
How does safely()
work?
The source code looks like this:
safely
#> function (.f, otherwise = NULL, quiet = TRUE)
#> {
#> .f <- as_mapper(.f)
#> force(otherwise)
#> check_bool(quiet)
#> function(...) capture_error(.f(...), otherwise, quiet)
#> }
#> <bytecode: 0x557c321c26b0>
#> <environment: namespace:purrr>
The real work is done in capture_error
which is defined in the package namespace. We can access it with the :::
operator. (Could also grab it from the function’s environment.)
purrr:::capture_error
#> function (code, otherwise = NULL, quiet = TRUE)
#> {
#> tryCatch(list(result = code, error = NULL), error = function(e) {
#> if (!quiet)
#> message("Error: ", conditionMessage(e))
#> list(result = otherwise, error = e)
#> })
#> }
#> <bytecode: 0x557c321d6510>
#> <environment: namespace:purrr>