[R-pkg-devel] best way the handle errors conditionally

Thierry Onkelinx thierry.onkelinx at inbo.be
Mon Mar 6 11:17:23 CET 2017


Dear all,

I'd like your advice on handling errors conditionally within a function.
Imagine a function that does several database operations. The user has the
option to run them inside a transaction. So the code has somewhere near the
top:

if (transaction) {
    DBI::dbBegin(conn)
}

At the end of the function there is a command which commits the transaction.

if (transaction) {
    DBI::dbCommit(conn)
}

If something goes wrong, one reverses the database operations by issuing
the DBI::dbRollback(conn) command. The first option for issuing that is to
use tryCatch(). The drawback is that the set of command can be a few
hundred lines, which harms readability when wrapping them into a tryCatch().

 tryCatch(
   {potentially long set of commands},
    error = function(e){
      if (transaction) {
        dbRollback(conn)
      }
      stop(e)
    }
)

Another options I've found is to set options(error = function(){}) I assume
that this has a permanent effect on the current R session? So I should
reset that as a part of the error handling?

What would be recommended: tryCatch() or options(error = ...)? Or are there
more / better solutions?

Best regards,


ir. Thierry Onkelinx
Instituut voor natuur- en bosonderzoek / Research Institute for Nature and
Forest
team Biometrie & Kwaliteitszorg / team Biometrics & Quality Assurance
Kliniekstraat 25
1070 Anderlecht
Belgium

To call in the statistician after the experiment is done may be no more
than asking him to perform a post-mortem examination: he may be able to say
what the experiment died of. ~ Sir Ronald Aylmer Fisher
The plural of anecdote is not data. ~ Roger Brinner
The combination of some data and an aching desire for an answer does not
ensure that a reasonable answer can be extracted from a given body of data.
~ John Tukey

	[[alternative HTML version deleted]]



More information about the R-package-devel mailing list