Created
October 8, 2014 03:24
-
-
Save robdaemon/6213eb0cac14e1e0860f to your computer and use it in GitHub Desktop.
pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| db.StartTransaction | |
| err := db.Execute | |
| if err != nil { | |
| db.Rollback | |
| return | |
| } | |
| err := db.Execute | |
| if err != nil { | |
| db.Rollback | |
| return | |
| } | |
| db.Commit | |
| return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, I agree, duplicating code like that is bad, but this is hardly a new problem that only exceptions can solve!
I'd consider most of the transaction handling code (Start/Rollback/Commit) boilerplate, so why not pull it out to begin with? Sort of a nano-framework. Or use goto, or defer.
I tossed a couple things together:
https://gist.github.com/jjhuff/77f61fb9daf72cff9e01
The first two options have the nice property that you can compose operations in the same transaction:
RunInTransaction(func(db *Database) error {
err := updateUserFullName(db)
if err == nil {
err = updatePassword(db)
}
return err
})