-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathrecover.go
73 lines (61 loc) · 1.67 KB
/
recover.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
62
63
64
65
66
67
68
69
70
71
72
73
package slogmulti
import (
"context"
"fmt"
"log/slog"
)
type RecoveryFunc func(ctx context.Context, record slog.Record, err error)
var _ slog.Handler = (*HandlerErrorRecovery)(nil)
type HandlerErrorRecovery struct {
recovery RecoveryFunc
handler slog.Handler
}
// RecoverHandlerError returns a slog.Handler that recovers from panics or error of the chain of handlers.
func RecoverHandlerError(recovery RecoveryFunc) func(slog.Handler) slog.Handler {
return func(handler slog.Handler) slog.Handler {
return &HandlerErrorRecovery{
recovery: recovery,
handler: handler,
}
}
}
// Enabled implements slog.Handler.
func (h *HandlerErrorRecovery) Enabled(ctx context.Context, l slog.Level) bool {
return h.handler.Enabled(ctx, l)
}
// Handle implements slog.Handler.
func (h *HandlerErrorRecovery) Handle(ctx context.Context, record slog.Record) error {
defer func() {
if r := recover(); r != nil {
if e, ok := r.(error); ok {
h.recovery(ctx, record, e)
} else {
h.recovery(ctx, record, fmt.Errorf("%+v", r))
}
}
}()
err := h.handler.Handle(ctx, record)
if err != nil {
h.recovery(ctx, record, err)
}
// propagate error
return err
}
// WithAttrs implements slog.Handler.
func (h *HandlerErrorRecovery) WithAttrs(attrs []slog.Attr) slog.Handler {
return &HandlerErrorRecovery{
recovery: h.recovery,
handler: h.handler.WithAttrs(attrs),
}
}
// WithGroup implements slog.Handler.
func (h *HandlerErrorRecovery) WithGroup(name string) slog.Handler {
// https://cs.opensource.google/go/x/exp/+/46b07846:slog/handler.go;l=247
if name == "" {
return h
}
return &HandlerErrorRecovery{
recovery: h.recovery,
handler: h.handler.WithGroup(name),
}
}