lost
lost

Reputation: 1669

use purrr lambda in tryCatch

I'd like to use purrr's lambda ~, if possible, instead of writing out function(e) in a tryCatch like the following:

tryCatch(suppressWarnings(load("foo.R")),
         error = function(e) {
           foo <- "a"
           save(foo, file = "foo.R")
         })

I don't actually use e as an argument, and ~ is 10 characters shorter than function(e). Simply swapping in ~ doesn't work, so I suspect I'm either misusing ~ , or tryCatch can't accomodate it.

file.remove("foo.R")
#> [1] TRUE
tryCatch(suppressWarnings(load("foo.R")),
         error = ~ {
           foo <- "a"
           save(foo, file = "foo.R")
         })
#> Error in value[[3L]](cond): attempt to apply non-function

(I'm aware file.exists can be used instead of a tryCatch structure for this kind of thing, but as the answer in this thread points out, there are other errors that could be thrown when trying to load a file.)

Upvotes: 2

Views: 147

Answers (1)

akrun
akrun

Reputation: 887511

An option would be to use as_mapper from purrr

library(purrr)
file.remove("foo.R")
#[1] TRUE
tryCatch(suppressWarnings(load("foo.R")),
     error = as_mapper(~ {
       foo <- "a"
       save(foo, file = "foo.R")
     }))
list.files()
#[1] "foo.R"

Upvotes: 2

Related Questions