greta-dev / greta

simple and scalable statistical modelling in R
https://greta-stats.org
Other
532 stars 63 forks source link

explore using classed errors in rlang's abort, warn, inform #375

Open njtierney opened 3 years ago

njtierney commented 3 years ago

https://rlang.r-lib.org/reference/abort.html

This allows for classed errors to be passed to the user as well as doing nicer printing of the error messages.

The user then might be able to control what happens with the error, e.g.,


# Give a class to the error:
abort("Something bad happened", "somepkg_bad_error")

# This will allow your users to handle the error selectively
tryCatch(
  somepkg_function(),
  somepkg_bad_error = function(err) {
    warn(conditionMessage(err)) # Demote the error to a warning
    NA                          # Return an alternative value
  }
)

as it states in the documentation

# Unhandled errors are saved automatically by `abort()` and can be
# retrieved with `last_error()`.
goldingn commented 3 years ago

Nice. I imagine this is for tidying up the error messages etc. But it might also be applied to the internal error handling here?

The cleanly() function is needed because TensorFlow errors when some routines (like Cholesky decomposition) have numerical issues, but instead we want to reject the parameter set, continue sampling, and record that the proposed parameters were rejected due to numerical issues (roughly equivalent to divergent transitions in Stan parlance).

njtierney commented 3 years ago

Yeah so my understanding is that we can give it a special class for these types of problems/errors, which might be useful for writing other interfaces to ignore/record these errors.

My rough understanding is that we can use with_handlers (described here) in place of tryCatch, and then we could use either abort in place of stop, or perhaps inform if we want to don't want to stop it in its tracks.

njtierney commented 3 years ago

See also the glubort helper function that a lot of tidyverse pkgs seem to use:

https://github.com/DavisVaughan/slider/blob/579c3042d51fc48fb400d2dd6810a2677756e695/R/utils.R#L1-L3

njtierney commented 1 year ago

Another helper is cli::cli_abort - which wraps the cli::format_error and then passing that to stop(msg, call. = FALSE) pattern.

njtierney commented 11 months ago

Just adding another description of classed errors here: https://www.mm218.dev/posts/2023-11-07-classed-errors/