From a54244d6db9c30e8fab5593602ce27b9c7c480a3 Mon Sep 17 00:00:00 2001 From: tidwall Date: Wed, 27 Apr 2022 17:05:38 -0700 Subject: [PATCH] Added wrapped error This commit wraps the errors that could, under rare a occasion, cause a panic. Allowing for a graceful recover by select conditions. Please see #82 for more info --- buntdb.go | 15 ++++++++++----- buntdb_test.go | 19 ++++++++++++++----- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/buntdb.go b/buntdb.go index 8c3408d..9b39e5c 100644 --- a/buntdb.go +++ b/buntdb.go @@ -7,6 +7,7 @@ package buntdb import ( "bufio" "errors" + "fmt" "io" "os" "sort" @@ -749,13 +750,13 @@ func (db *DB) Shrink() error { if err := db.file.Close(); err != nil { return err } - // Any failures below here is really bad. So just panic. + // Any failures below here are really bad. So just panic. if err := os.Rename(tmpname, fname); err != nil { - panic(err) + panicErr(err) } db.file, err = os.OpenFile(fname, os.O_CREATE|os.O_RDWR, 0666) if err != nil { - panic(err) + panicErr(err) } pos, err := db.file.Seek(0, 2) if err != nil { @@ -766,6 +767,10 @@ func (db *DB) Shrink() error { }() } +func panicErr(err error) error { + panic(fmt.Errorf("buntdb: %w", err)) +} + // readLoad reads from the reader and loads commands into the database. // modTime is the modified time of the reader, should be no greater than // the current time.Now(). @@ -1209,10 +1214,10 @@ func (tx *Tx) Commit() error { // should be killed to avoid corrupting the file. pos, err := tx.db.file.Seek(-int64(n), 1) if err != nil { - panic(err) + panicErr(err) } if err := tx.db.file.Truncate(pos); err != nil { - panic(err) + panicErr(err) } } tx.rollbackInner() diff --git a/buntdb_test.go b/buntdb_test.go index 4ef4fd4..4b37db2 100644 --- a/buntdb_test.go +++ b/buntdb_test.go @@ -2903,9 +2903,18 @@ func TestEstSize(t *testing.T) { assert.Assert(estIntSize(-12) == 3) assert.Assert(estIntSize(-124) == 4) }) - // t.Run("estI - // // dbi := dbItem{ - // // key: "hello", - // // value: " - // // } +} + +func TestWrappedError(t *testing.T) { + defer func() { + if err, ok := recover().(error); ok { + if strings.HasPrefix(err.Error(), "buntdb: ") { + err := errors.Unwrap(err) + if err.Error() != "my fake error" { + t.Fatal("!") + } + } + } + }() + panicErr(errors.New("my fake error")) }