Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make default panic handler could be customized #1182

Merged
merged 2 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions consumer/push_consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
13 changes: 9 additions & 4 deletions primitive/base.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
21 changes: 21 additions & 0 deletions primitive/base_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ limitations under the License.
package primitive

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -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")
})
})
}
Loading