forked from coder/coder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecover.go
More file actions
47 lines (40 loc) · 1.12 KB
/
recover.go
File metadata and controls
47 lines (40 loc) · 1.12 KB
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
package httpmw
import (
"context"
"net/http"
"runtime/debug"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/coderd/tracing"
)
func Recover(log slog.Logger) func(h http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
r := recover()
// Reverse proxying (among other things) may panic with
// http.ErrAbortHandler when the request is aborted. It's not a
// real panic so we shouldn't log them.
//
//nolint:errorlint // this is how the stdlib does the check
if r != nil && r != http.ErrAbortHandler {
log.Warn(context.Background(),
"panic serving http request (recovered)",
slog.F("panic", r),
slog.F("stack", string(debug.Stack())),
)
var hijacked bool
if sw, ok := w.(*tracing.StatusWriter); ok {
hijacked = sw.Hijacked
}
// Only try to write errors on
// non-hijacked responses.
if !hijacked {
httpapi.InternalServerError(w, nil)
}
}
}()
h.ServeHTTP(w, r)
})
}
}