r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
405 stars 56 forks source link

[question] Catch class and method when returning an error #105

Closed denrou closed 7 years ago

denrou commented 7 years ago

Hi,

Consider this simple class:

my_awesome_class <- R6::R6Class(
  "my_awesome_class",
  public = list(
    x = NA,
    initialize = function(x) {
      self$x = x
    },
    lets_add = function(y) {
      self$x + y
    }
  )
)

now if I do

x <- my_awesome_class$new(1)
x$lets_add(2)
[1] 3

everything runs smoothly. But sometimes I make some mistakes:

x$lets_add("A")
Error in self$x + y : non-numeric argument to binary operator

The error is the same as the one returned by 1 + "A". I was wondering if we could imagine a catch mechanism on R6 class for the errors to be more exhaustive. For example, we could return:

x$lets_add("A")
Error in method lets_add of class my_awesome_class with message:
Error in self$x + y : non-numeric argument to binary operator
wch commented 7 years ago

I don't know of a good way to do this -- that's how R in general reports errors.

After encountering an error, you can use traceback() to see the call stack, or you can set the error option to call traceback() so that it automatically shows the call stack at an error. This will only help for users that know how do this, though.

> x$lets_add("A")
Error in self$x + y : non-numeric argument to binary operator
> traceback()
1: x$lets_add("A")
> 
> options(error = function() traceback(3))
> x$lets_add("A")
Error in self$x + y : non-numeric argument to binary operator
1: x$lets_add("A")