Newer
Older
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
package orusapi
import (
"fmt"
"net/http"
"runtime/debug"
"github.com/getsentry/sentry-go"
jsoniter "github.com/json-iterator/go"
"github.com/rs/zerolog"
)
// CatchPanics catches the panics and log them as errors
func CatchPanics(next http.Handler) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
defer func() {
if r := recover(); r != nil {
log := zerolog.Ctx(req.Context())
exc := zerolog.Dict().
Str("value", fmt.Sprintf("%#v", r)).
Str("type", fmt.Sprintf("%T", r))
stack := sentry.NewStacktrace()
stack.Frames = stack.Frames[:len(stack.Frames)-1]
b, err := jsoniter.Marshal(stack)
if err != nil {
log.Err(err).Msg("Could not marshal stacktrace, fallback to plain debug.Stack()")
b = debug.Stack()
exc = exc.Str("plainstack", string(b))
} else {
exc = exc.RawJSON("stacktrace", b)
}
log.Error().Dict("exception", exc).Msg("Caught a panic")
rw.WriteHeader(http.StatusInternalServerError)
}
}()
next.ServeHTTP(rw, req)
})
}