Skip to contents

Returning a default

fallback() catches a failure and returns a default instead of signalling it.

safe_sqrt := fallback(value = NA_real_) %@% function(x) {
  if (x < 0) stop("negative") else sqrt(x)
}
safe_sqrt(4)
## [1] 2
safe_sqrt(-1)
## [1] NA

To compute the result from the failure, pass a handler. It receives the condition:

describe := fallback(handler = function(cnd) conditionMessage(cnd)) %@%
  function() stop("boom")
describe()
## [1] "boom"

Only errors are caught by default. Set class to catch other conditions, such as class = "warning". A caught condition ends the call, as with tryCatch().

Stacking with retry and the circuit breaker

Put fallback() outermost. The default is then used only once retry() has given up, or once circuit_breaker() has opened:

calls <- 0
fetch := fallback(value = "cached") %@%
  circuit_breaker(failures = 3) %@%
  retry(stop = stop_after_attempt(2)) %@%
  function(url) {
    calls <<- calls + 1
    stop("down")
  }

fetch("x")
## [1] "cached"
calls
## [1] 2

Promises

async_fallback() does the same for functions that return a promise. The promise resolves to the default if the function rejects with a matching condition, and other rejections carry on unchanged. It needs the promises package.

f := async_fallback(value = "default") %@% function() stop("boom")
promises::then(f(), print)

Running once

once() runs a function on its first successful call and returns that result every time after, ignoring later arguments. It suits setup that should happen a single time.

setup := once %@% function() {
  cat("setting up\n")
  42
}
setup()
## setting up
## [1] 42
setup()
## [1] 42

An error stores nothing, so the next call tries again. Unlike cache(), which keeps a result per set of arguments, once() keeps one result whatever the arguments.

async_once is the version for functions that return a promise. It keeps the resolved value, makes calls that arrive while the first is running share its promise, and stores nothing on a rejection, so the next call tries again.

setup := async_once %@% function() promises::promise_resolve(42)
promises::then(setup(), print)