I am writing some transaction begin/commit/rollback functions, and I want to pair the block to prevent forgot commit
I write like this:
func (foo *Foo) Bar() (err error) {
foo.Begin()
defer foo.End(&err)
//some business code
return
}
func (foo *Foo) End(eptr *error) {
// if recover
if r := recover(); r != nil {
debug.PrintStack()
*eptr = r.(error)
}
var err = *eptr
if err != nil {
foo.Rollback()
} else {
foo.Commit()
}
}
It works, but it uses the "pointer to interface", I cannot find the specifications about pointer to interface.
So, I am not sure this code is OK enough. Could you give some suggestions?
thanks to teyzer and Corey Ogburn, this is my fixed solution:
func (foo *Foo) Bar() (err error) {
foo.Begin()
defer func() { foo.End(err) }()
defer func() {
if r := recover(); r != nil {
debug.PrintStack()
err = makeError(r)
}
} ()
//some business code
return
}
func (foo *Foo) End(err error) {
if err != nil {
foo.Rollback()
} else {
foo.Commit()
}
}