Home > database >  Can I access the last computed result before a function 'stop's?
Can I access the last computed result before a function 'stop's?

Time:09-30

Consider this code:

bad_function <- function() {
    # a lot of code
    x <- 1
    stop("error")
}

tryCatch(bad_function(), error = function(cond) {x})

Obviously, x is not accessible in the error handler. But is there another way to access the value of x without changing bad_function? Alternatively, is there a way to patch bad_function to skip over stop("error") and return x without having to copy all that # a lot of code?

CodePudding user response:

This works if the result you are looking for is named (and the you know the name - here, x):

bad_function <- function() {
    # a lot of code
    x <- 1
    stop("error")
}

.old_stop <- base::stopifnot
.new_stop <- function(...) {
    parent.frame()$x
}

assignInNamespace("stop", .new_stop, "base")
bad_function()
assignInNamespace("stop", .old_stop, "base")

I still wonder if there are better solutions.

CodePudding user response:

You could assign the value simultaneously to x in the function environment, as well to another x in an external say debug environment that you defined beforehand.

ev1 <- new.env()

bad_function <- function() {
  env <- new.env(parent=baseenv())
  # a lot of code
  x <- ev1$x <- 1
  stop("error")
}

tryCatch(bad_function(), error = function(e) ev1$x)
# [1] 1

The advantage is that .GlobalEnv stays clear (apart from the environment of course).

ls()
# [1] "bad_function" "ev1"         
  • Related