This is a follow up question to this question which didn't get any traction. I realise now that this has nothing to do with purrr::possibly
specifically as tryCatch
also doesn't work like I thought.
I'm trying to write a function which will run any other arbitrary function without throwing an error. This might not be good practice but I want to understand why this does not work:
library(ggplot2)
## function I thought I could use to run other functions safely
safe_plot <- function(.FUN, ...) {
tryCatch({
.FUN(...)
},
error = function(e) {
message(e)
print("I have got passed the error")
})
}
## Simple plot function
plot_fun <- function(df) {
ggplot(df, aes(xvar, yvar)) +
geom_point()
}
## Works for good data
some_data <- data.frame(xvar = 1:10, yvar = 1:10)
safe_plot(.FUN = plot_fun, df = some_data)
## Works here for data that is not defined:
> safe_plot(.FUN = plot_fun, df = not_defined)
object 'not_defined' not found[1] " I have got passed the error"
## Falls over for an empty data frame
empty_data <- data.frame()
safe_plot(.FUN = plot_fun, df = empty_data)
## Why does't this get past this error and print the message?
> safe_plot(.FUN = plot_fun, df = empty_data)
Error in FUN(X[[i]], ...) : object 'xvar' not found
Why doesn't the last call get to the print statement? I suspect I am abusing tryCatch but I don't know why. Reading some other questions (1, 2) I checked for the class of what tryCatch returns:
> ## What is returned
> empty_data <- data.frame()
> what_is_this <- safe_plot(.FUN = plot_fun, df = empty_data)
> what_is_this
Error in FUN(X[[i]], ...) : object 'xvar' not found
> class(what_is_this)
[1] "gg" "ggplot"
So in the plot function above ggplot(df,
does not fail because there is a df
of empty_data
. The error must occur in aes(xar,
. But why does this not return an error class and instead returns a ggplot?