/
recovery.go
80 lines (67 loc) · 1.84 KB
/
recovery.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
74
75
76
77
78
79
80
package internal
import (
"errors"
"fmt"
"log/slog"
"net/http"
"runtime/debug"
"cloud.google.com/go/errorreporting"
)
type recoveryHandler struct {
l *slog.Logger
er ErrorReporter
handler http.Handler
}
// RecoveryHandler is HTTP middleware that recovers from a panic, writes a
// 500, reports the panic, logs the panic and continues to the next handler.
func RecoveryHandler(l *slog.Logger, er ErrorReporter) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return &recoveryHandler{l: l, er: er, handler: h}
}
}
func (h recoveryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer func() {
if rec := recover(); rec != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(`{"error":"internal server error"}`))
h.handle(req, &recovered{rec, debug.Stack()})
}
}()
h.handler.ServeHTTP(w, req)
}
func (h recoveryHandler) handle(r *http.Request, err error) {
stack, _ := stackFromRecovered(err)
e := errorreporting.Entry{
Error: err,
Stack: stack,
Req: r,
}
h.er.Report(e)
h.l.ErrorContext(r.Context(), err.Error(), "error", err, "stack", string(stack))
}
// recovered represents the return value from a call to recover.
type recovered struct {
// p is the error value passed to the call of panic.
p interface{}
// stack is the panic stack trace.
stack []byte
}
var _ error = (*recovered)(nil)
// Error implements error.
func (e *recovered) Error() string {
if err, ok := e.p.(error); ok {
return err.Error()
}
return fmt.Sprintf("panic: %v", e.p)
}
// stackFromRecovered returns a stack trace and true if the recovdered has a
// stack trace created by this package.
//
// Otherwise it returns nil and false.
func stackFromRecovered(err error) ([]byte, bool) {
var rec *recovered
if errors.As(err, &rec) {
return rec.stack, true
}
return nil, false
}