Skip to content

Instantly share code, notes, and snippets.

@alecthomas
Last active August 29, 2015 14:02
Show Gist options
  • Save alecthomas/bb00f91b0f1c884e01b9 to your computer and use it in GitHub Desktop.
Save alecthomas/bb00f91b0f1c884e01b9 to your computer and use it in GitHub Desktop.
CommitOrRollbackOnError commits or rolls back a transaction based on the value of an error reference.
// CommitOrRollbackOnError commits or rolls back a transaction based on the
// value of an error reference. It helps avoid error prone boilerplate
// rollback calls.
//
// Most useful in a defer statement:
//
// tx, err := db.Begin()
// if err != nil {
// return err
// }
// defer CommitOrRollbackOnError(tx, &err)
//
// _, err = tx.Exec("INSERT INTO x ...")
// if err != nil {
// return err
// }
// _, err = tx.Exec("INSERT INTO y ...")
// if err != nil {
// return err
// }
//
// return nil
//
// Replacing:
//
// tx, err := db.Begin()
// if err != nil { return err }
//
// // _, err = tx.Exec("INSERT INTO x ...")
// if err != nil {
// rx.Rollback()
// return err
// }
// _, err = tx.Exec("INSERT INTO y ...")
// if err != nil {
// tx.Rollback()
// return err
// }
//
// tx.Commit()
// return nil
//
// Note that error values assigned in nested scopes will create
// completely new variables and this trick will not work.
func CommitOrRollbackOnError(tx *sql.Tx, err *error) {
if *err == nil {
tx.Commit()
} else {
tx.Rollback()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment