diff --git a/consumer/push_consumer.go b/consumer/push_consumer.go index db6a37e3..e6ec3e50 100644 --- a/consumer/push_consumer.go +++ b/consumer/push_consumer.go @@ -1111,6 +1111,9 @@ func (pc *pushConsumer) consumeMessageConcurrently(pq *processQueue, mq *primiti go primitive.WithRecover(func() { defer func() { if err := recover(); err != nil { + if primitive.DefaultPanicHandler != nil { + primitive.DefaultPanicHandler(err) + } rlog.Error("consumeMessageConcurrently panic", map[string]interface{}{ rlog.LogKeyUnderlayError: err, rlog.LogKeyStack: utils.GetStackAsString(false), diff --git a/primitive/base.go b/primitive/base.go index 0042785d..6ddb32e8 100644 --- a/primitive/base.go +++ b/primitive/base.go @@ -87,14 +87,19 @@ func verifyIP(ip string) error { type PanicHandler func(interface{}) -func DefaultPanicHandler(interface{}) { - return -} +// primitive.DefaultPanicHandler = func(i interface{}) { +// sentry.CaptureMessage(fmt.Sprintf("%+v", i), nil) +// } +var DefaultPanicHandler PanicHandler func WithRecover(fn func(), handlers ...PanicHandler) { defer func() { if len(handlers) == 0 { - handlers = append(handlers, DefaultPanicHandler) + if DefaultPanicHandler != nil { + handlers = append(handlers, DefaultPanicHandler) + } else { + handlers = append(handlers, func(interface{}) {}) + } } for _, handler := range handlers { if handler != nil { diff --git a/primitive/base_test.go b/primitive/base_test.go index db947c4f..51d7aa1f 100644 --- a/primitive/base_test.go +++ b/primitive/base_test.go @@ -18,6 +18,7 @@ limitations under the License. package primitive import ( + "fmt" "testing" "github.com/stretchr/testify/assert" @@ -74,3 +75,23 @@ func TestBase(t *testing.T) { b = []string{"a", "c"} assert.True(t, Diff(a, b)) } + +func TestWithRecover(t *testing.T) { + ass := assert.New(t) + + DefaultPanicHandler = nil + ass.NotPanics(func() { + WithRecover(func() { + panic("test") + }) + }) + + DefaultPanicHandler = func(i interface{}) { + fmt.Println("panic test") + } + ass.NotPanics(func() { + WithRecover(func() { + panic("test") + }) + }) +}