From ac4838472da343493c54c7649deb3b20669f8c3b Mon Sep 17 00:00:00 2001 From: Ben Johnson Date: Fri, 11 Jul 2014 09:54:10 -0600 Subject: Recover from panics appropriately. This commit adds a defer handler to ensure that transactions are always closed out - even in the event of a panic within user code. It's recommended that applications always fail in the event of a panic but some packages such as net/http will automatically recover which is a problem (IHMO). --- db.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'db.go') diff --git a/db.go b/db.go index b839e23..4df79e2 100644 --- a/db.go +++ b/db.go @@ -440,6 +440,13 @@ func (db *DB) Update(fn func(*Tx) error) error { return err } + // Make sure the transaction rolls back in the event of a panic. + defer func() { + if t.db != nil { + t.rollback() + } + }() + // Mark as a managed tx so that the inner function cannot manually commit. t.managed = true @@ -464,6 +471,13 @@ func (db *DB) View(fn func(*Tx) error) error { return err } + // Make sure the transaction rolls back in the event of a panic. + defer func() { + if t.db != nil { + t.rollback() + } + }() + // Mark as a managed tx so that the inner function cannot manually rollback. t.managed = true -- cgit v1.2.3