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

Duncan Murdoch murdoch.duncan at gmail.com
Mon Mar 6 13:18:47 CET 2017


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



More information about the R-package-devel mailing list