Skip to content
Prev 57173 / 63421 Next

Determining the exit code of an "almost finished" R script

Sorry for the late reply, it took a couple of iterations (and some
days off) to find a feasible solution without splitting the helper
function into two -- please see below if interested.
On Sat, Jun 8, 2019 at 6:50 PM Duncan Murdoch <murdoch.duncan at gmail.com> wrote:
Yes, you are absolutely right -- still, I really wanted to make this
work by calling only one function at the beginning of an R script
(actually, hundreds of R scripts and without an explicit R function
call, but doing that in a package's .onLoad function).

What I came up with is probably not too elegant ... and might have
some edge cases, but seems to do the trick, so thus turned out to be a
reasonable solution for now:
- overriding the default "error" option to set an env var
- check that env var at the end of the script via "reg.finalizer"
triggered on exit

Quick example:

```r
library(logger)

options(error = function() {
    Sys.setenv(R_ERROR_HAPPENED = TRUE)
    quit(status = 1)
})

reg.finalizer(e = environment(), f = function(...) {
    if (Sys.getenv('R_ERROR_HAPPENED') != '') {
        log_error(skip_formatter(paste('Seems like there was an error
previously:', geterrmessage())))
    } else {
        log_info('All good!')
    }
}, onexit = TRUE)

1 + dasf
```
Message-ID: <CAPvvxJXOePsZnsk=i6Q5QJRedVgjHVLincpRFPthz_UptZ0Yrw@mail.gmail.com>
In-Reply-To: <2360288f-52fb-096b-beb7-f5252844b2a2@gmail.com>