defer_errors: Run a block of code, collecting deferrable errors

Description Usage Arguments Details Examples

View source: R/defer.R

Description

Run a block of code, collecting any deferrable_error calls that occur. Ordinary errors will be thrown immediately.

Usage

1
defer_errors(expr, handler = stop)

Arguments

expr

An expression to evaluate

handler

The final handler for the deferred errors. The default is stop which will raise the collected error. Alternatively, use return to return the error

Details

The error object will contain an element errors with the deferred errors, each of which will contain elements message, call (the call that precedes deferrable_error and calls which contains the "interesting" part of the stack trace (i.e., only calls below the defer_errors infrastructure).

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
check_positive <- function(x) {
  if (x < 0) {
    deferrable_error(paste("got a negative number:", x))
  }
}
err <- tryCatch(
  defer::defer_errors({
    check_positive(0)
    check_positive(-1)
    check_positive(-2)
  }),
  error = identity)
err

# Directly return the error:
err <- defer::defer_errors({
  check_positive(0)
  check_positive(-1)
  check_positive(-2)
}, handler = return)

# Stack traces are included to improve downstream reporting:
f <- function(x) {
  g(x)
}
g <- function(x) {
  check_positive(x)
}
err <- defer_errors({
  f(0)
  f(-1)
  f(-2)
}, handler = return)
err$errors[[1]]$calls

reside-ic/defer documentation built on Nov. 5, 2019, 3:06 a.m.