nathaneastwood
nathaneastwood

Reputation: 3764

Is it possible to stop and return

I have run into this problem a few times recently. I have some R code whereby if a certain thing happens, I want to stop() and exit the function, therefore returning an exit code. However I also want to return() the latest copy of an object from within the function which is created in that function.

Is this possible?

As a really silly example, see the below code. Wherever you see a stop() I would also like to return() the value of i. NOTE: I know this isn't how you would write this function. It's simply an example

tmp <- function() {
  i <- 1
  if (i == 3) {
    stop()
  }
  i <- i + 1
  if (i == 3) {
    stop()
  }
  i <- i + 1
  if (i == 3) {
    stop()
  }
}

Upvotes: 3

Views: 563

Answers (1)

Joris C.
Joris C.

Reputation: 6234

You can use rlang's abort to return additional data with an error object:

library(rlang)

## dummy function
fun <- function(x, error = FALSE) {
  x <- x + 1
  if(error)
    abort("Error!", x = x)
  return(x)
}

## no error
fun(1, error = FALSE)
#> [1] 2

## error 
fun(2, error = TRUE)
#> Error!

## display last error
last_error()
#> <error>
#> message: Error!
#> class:   `rlang_error`
#> backtrace:
#>  1. global::fun(2, error = TRUE)
#> Call `rlang::last_trace()` to see the full backtrace

last_error()$x
#> [1] 3

Upvotes: 1

Related Questions