[R] Custom error handling without stopping execution?

Thomas Nyberg twn2103 at columbia.edu
Wed Apr 15 00:57:25 CEST 2015


Hello I've been trying to produce a general error logging/handling
framework that I can live with. I'll post the code first:

example.R
---------------------------
good_main <- function() {
    for (i in 1:2) {
        bad_function()
    }
}

bad_main <- function() {
    for (i in 1:2) {
        try(bad_function())
    }
}

Stop <- function() {
    call_stack <- sys.calls()
    err_message <- geterrmessage()
    # Drop the final function (which is this one) from the
    # call_stack.
    call_stack <- head(call_stack, length(call_stack) - 1)
    # Convert to strings.
    call_stack <- lapply(call_stack, capture.output)
    call_stack <- unlist(call_stack)
    call_stack <- paste(call_stack, collapse="\n")

    print(call_stack)
}

options(error = Stop)

bad_function <- function() {
    stop("Bad function.")
}

good_main()
bad_main()
---------------------------

The following is the result of running this on my end:

---------------------------
$ Rscript example.R
Error in bad_function() : Bad function.
Calls: good_main -> bad_function
[1] "good_main()\nbad_function()\nstop(\"Bad function.\")"
Error in bad_function() : Bad function.
Error in bad_function() : Bad function.
---------------------------

My problem is the following line:

	[1] "good_main()\nbad_function()\nstop(\"Bad function.\")"

This is only printed once because the good_main() function is ending its
execution when the error occurs. The bad_main() function does not, but
that one seems to kill my stack_trace (which is the whole point of my
doing this). How to I use a custom error handler (as in good_main())
_without_ stopping execution (as is occurring in bad_main())?

Thanks for any help.

Cheers,
Thomas



More information about the R-help mailing list