From bac8881d11e9d338d35d4424ad4a6f36e7d8e61d Mon Sep 17 00:00:00 2001 From: WeizhongTu Date: Thu, 12 Dec 2024 10:33:44 +0800 Subject: [PATCH 1/2] make default panic handler could be customized --- primitive/base.go | 13 +++++++++---- primitive/base_test.go | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) 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") + }) + }) +} From dc36a3779dafd56caa4acdf8763ffe85639da266 Mon Sep 17 00:00:00 2001 From: WeizhongTu Date: Thu, 12 Dec 2024 10:37:39 +0800 Subject: [PATCH 2/2] feat: add primitive.DefaultPanicHandler --- consumer/push_consumer.go | 3 +++ 1 file changed, 3 insertions(+) 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),