Skip to content

Commit

Permalink
make default panic handler could be customized (#1182)
Browse files Browse the repository at this point in the history
* make default panic handler could be customized

* feat: add primitive.DefaultPanicHandler
  • Loading branch information
twz915 authored Dec 12, 2024
1 parent dd3dbcc commit abae4a0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
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")
})
})
}

0 comments on commit abae4a0

Please sign in to comment.