/
messagehandler.go
61 lines (52 loc) · 1.54 KB
/
messagehandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Package messagehandler contains useful helpers for recovering
// from panic conditions at runtime and logging their trace.
package messagehandler
import (
"context"
"fmt"
"runtime/debug"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)
const noMsgData = "message contains no data"
var log = logrus.WithField("prefix", "message-handler")
// SafelyHandleMessage will recover and log any panic that occurs from the
// function argument.
func SafelyHandleMessage(ctx context.Context, fn func(ctx context.Context, message *pubsub.Message) error, msg *pubsub.Message) {
defer HandlePanic(ctx, msg)
// Fingers crossed that it doesn't panic...
if err := fn(ctx, msg); err != nil {
// Report any error on the span, if one exists.
if span := trace.FromContext(ctx); span != nil {
span.SetStatus(trace.Status{
Code: trace.StatusCodeInternal,
Message: err.Error(),
})
}
}
}
// HandlePanic returns a panic handler function that is used to
// capture a panic.
func HandlePanic(ctx context.Context, msg *pubsub.Message) {
if r := recover(); r != nil {
printedMsg := noMsgData
if msg != nil {
printedMsg = msg.String()
}
log.WithFields(logrus.Fields{
"r": r,
"msg": printedMsg,
}).Error("Panicked when handling p2p message! Recovering...")
debug.PrintStack()
if ctx == nil {
return
}
if span := trace.FromContext(ctx); span != nil {
span.SetStatus(trace.Status{
Code: trace.StatusCodeInternal,
Message: fmt.Sprintf("Panic: %v", r),
})
}
}
}