Skip to content

Commit

Permalink
feat(recovery): Add recovery (#25)
Browse files Browse the repository at this point in the history
  • Loading branch information
flc1125 authored Oct 31, 2023
1 parent 53442f1 commit 4dceb84
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
47 changes: 47 additions & 0 deletions recovery/recovery.go
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()
}
28 changes: 28 additions & 0 deletions recovery/recovery_test.go
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))
}

0 comments on commit 4dceb84

Please sign in to comment.