# The example needs to be complex since it's about nested functions, sorry
# Let's say you have an internal function that is dispatched into several
# user-level functions
my_mean = function(x, drop_na = FALSE){
set_hook()
my_mean_internal(x = x, drop_na = drop_na)
}
my_mean_skip_na = function(x){
set_hook()
my_mean_internal(x = x, drop_na = TRUE)
}
my_mean_internal = function(x, drop_na){
# simple check
if(!is.numeric(x)){
# note that we use string interpolation with stringmagic.
stop_hook("The argument `x` must be numeric. PROBLEM: it is of class {enum.bq ? class(x)}.")
}
if(drop_na){
return(mean(x, na.rm = TRUE))
} else {
return(mean(x, na.rm = FALSE))
}
}
# Let's run the function with a wrong argument
x = "five"
try(my_mean(x))
# => the error message reports that the error comes from my_mean
# and *not* my_mean_internal
Run the code above in your browser using DataLab