Try Catch

Colin Fay

2018-04-20

attempt

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

library(attempt)
attempt(log("a"))
# Error: argument non numérique pour une fonction mathématique

attempt(log("a"), msg = "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 !

Of course the result is returned if there is one:

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

As with try, the result cant be saved as an error object :

a <- attempt(log("a"), msg = "Nop !", verbose = TRUE)
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 !>

silent_attempt

silent_attempt is a wrapper around silently (see the adverbs vignette 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: argument non numérique pour une fonction mathématique
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.