R/on_error.R

Defines functions on_error

Documented in on_error

#' Add a function to be run on error
#'
#' This function behaves as `on.exit()`, but is run on error, and supports mappers.
#'
#' @param f a function to call on error
#'
#' @return A local error handler.
#' @export
#'
#' @examples
#'
#' y <- function(num){
#'   on_error(~ write( Sys.time(), "error_log.txt", append = TRUE) )
#'   log(num)
#'}
#'
on_error <- function(f){

  f <- rlang::as_function(f)

  old <- do.call(options, as.list( c("error" = f) ))

  do.call(
    options,
    list("error" = f),
    envir = parent.frame()
  )

  do.call(
    on.exit,
    list(substitute(options(old)),
         add = TRUE),
    envir = parent.frame()
  )

}

Try the attempt package in your browser

Any scripts or data that you put into this service are public.

attempt documentation built on May 4, 2020, 1:05 a.m.