On 06/03/2017 5:17 AM, Thierry Onkelinx wrote:
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().

You could put the long set of commands into their own function, perhaps locally defined within the main function. For example,

longset <- function() { ... }
if (transaction) {
    DBI::dbBegin(conn)
}
tryCatch(
  longset()
  error = function(e){
     if (transaction) {
       dbRollback(conn)
     }
     stop(e)
   }
)

Duncan Murdoch

______________________________________________
R-package-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-package-devel

Reply via email to