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
41 lines (35 loc) · 861 Bytes
/
recover.go
File metadata and controls
41 lines (35 loc) · 861 Bytes
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
package httpmw
import (
"context"
"net/http"
"runtime/debug"
"cdr.dev/slog"
"github.com/coder/coder/coderd/httpapi"
"github.com/coder/coder/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()
if r != nil {
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)
})
}
}