Add error check for Transaction

This commit is contained in:
Jinzhu 2020-11-19 10:45:17 +08:00
parent a1a30c38de
commit e7f45d5b01
1 changed files with 7 additions and 3 deletions

View File

@ -472,7 +472,7 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er
if committer, ok := db.Statement.ConnPool.(TxCommitter); ok && committer != nil { if committer, ok := db.Statement.ConnPool.(TxCommitter); ok && committer != nil {
// nested transaction // nested transaction
db.SavePoint(fmt.Sprintf("sp%p", fc)) err = db.SavePoint(fmt.Sprintf("sp%p", fc)).Error
defer func() { defer func() {
// Make sure to rollback when panic, Block error or Commit error // Make sure to rollback when panic, Block error or Commit error
if panicked || err != nil { if panicked || err != nil {
@ -480,7 +480,9 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er
} }
}() }()
err = fc(db.Session(&Session{})) if err == nil {
err = fc(db.Session(&Session{}))
}
} else { } else {
tx := db.Begin(opts...) tx := db.Begin(opts...)
@ -491,7 +493,9 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er
} }
}() }()
err = fc(tx) if err = tx.Error; err == nil {
err = fc(tx)
}
if err == nil { if err == nil {
err = tx.Commit().Error err = tx.Commit().Error