Try Catch

Colin Fay

2019-04-08

attempt

attempt() is a wrapper around base try() that allows you to insert a custom messsage on error.

attempt(log("a"))
#> Error: non-numeric argument to mathematical function
# Error: non-numeric argument to mathematical function
attempt(log("a"), msg = "Nop !")
#> Error: Nop !
# Error: Nop !

You can make it verbose (i.e. returning the expression):

attempt(log("a"), msg = "Nop !", verbose = TRUE)
#> Error in log("a"): Nop !
# Error in log("a"): Nop !

Of course the result is returned if there is one:

attempt(log(1), msg = "Nop !", verbose = TRUE)
#> [1] 0
# [1] 0

As with try(), the result can be saved as an error object:

a <- attempt(log("a"), msg = "Nop !", verbose = TRUE)
#> Error in log("a"): Nop !
a
#> [1] "Error in log(\"a\"): Nop !\n"
#> attr(,"class")
#> [1] "try-error"
#> attr(,"condition")
#> <simpleError in log("a"): Nop !>
# [1] "Error in log(\"a\"): Nop !\n"
# attr(,"class")
# [1] "try-error"
# attr(,"condition")
# <simpleError in log("a"): Nop !>

You can check if the result is an error with is_try_error()

a <- attempt(log("a"), msg = "Nop !", verbose = FALSE)
#> Error: Nop !
is_try_error(a)
#> [1] TRUE

silent_attempt

silent_attempt() is a wrapper around silently() (see further down for more info) and attempt(). It attempts to run the expr, stays silent if the expression succeeds, and returns error or warnings if any.

silent_attempt(log("a"))
#> Error: non-numeric argument to mathematical function
# Error: non-numeric argument to mathematical function
silent_attempt(log(1))

try catch

You can write a try catch with these params:

In .e and .f, the .x refers to the error / warning object.

With mappers

As usual, the handlers are set only if you call them:

Traditionnal way

{attempt} is flexible in how you can specify your arguments.

You can, as you do with {base} tryCatch(), use a plain old function:

You can even mix both:

try_catch_df()

try_catch_df() returns a tibble with the call, the error message if any, the warning message if any, and the value of the evaluated expression or “error”. The values will always be contained in a list-column.

map_try_catch()

map_try_catch() and map_try_catch_df() allow you to map on a list of arguments l, to be evaluated by the function in fun.