-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
75 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package recovery | ||
|
||
type options struct { | ||
handler func(err interface{}) | ||
} | ||
|
||
type Option func(o *options) | ||
|
||
func WithHandler(handler func(err interface{})) Option { | ||
return func(o *options) { | ||
o.handler = handler | ||
} | ||
} | ||
|
||
type Recovery struct { | ||
opt *options | ||
} | ||
|
||
func New(opts ...Option) *Recovery { | ||
o := &options{} | ||
|
||
for _, opt := range opts { | ||
opt(o) | ||
} | ||
|
||
if o.handler == nil { | ||
o.handler = func(err interface{}) { | ||
panic(err) | ||
} | ||
} | ||
|
||
return &Recovery{ | ||
opt: o, | ||
} | ||
} | ||
|
||
func (r *Recovery) Wrap(f func() error) error { | ||
defer func() { | ||
if err := recover(); err != nil { | ||
if r.opt.handler != nil { | ||
r.opt.handler(err) | ||
} | ||
} | ||
}() | ||
|
||
return f() | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
package recovery | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestRecovery_Wrap(t *testing.T) { | ||
fn := func() error { | ||
panic("test") | ||
|
||
return nil | ||
} | ||
|
||
// default | ||
r := New() | ||
assert.Panics(t, func() { | ||
_ = r.Wrap(fn) | ||
}) | ||
|
||
// with handler | ||
r = New(WithHandler(func(err interface{}) { | ||
assert.Equal(t, "test", err) | ||
})) | ||
|
||
assert.NoError(t, r.Wrap(fn)) | ||
} |