forked from noxecane/anansi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
50 lines (41 loc) · 1.41 KB
/
errors.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
package middleware
import (
"context"
"net/http"
"runtime/debug"
"github.com/random-guys/go-siber"
"github.com/rs/zerolog"
)
// Recoverer creates a middleware that handles panics from chi controllers. It handles
// printing(optionally stack trace in dev env) and responding to the client for all
// errors except JSendErrors. Note that all errors(bar JSendError) respond with a 500
func Recoverer(env string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
defer func() {
// abort early if request timed out
if r.Context().Err() == context.DeadlineExceeded {
http.Error(w, http.StatusText(http.StatusGatewayTimeout), http.StatusGatewayTimeout)
}
if rvr := recover(); rvr != nil && rvr != http.ErrAbortHandler {
if e, ok := rvr.(siber.JSendError); ok {
siber.SendError(r, w, e)
} else {
ctx := r.Context()
// always log errors regardless of the type
log := zerolog.Ctx(ctx)
err := rvr.(error) // it would be serious if this wasn't an error
log.Err(err).Msg("")
// give dev a chance to trace unknown errors
if env == "dev" || env == "test" {
debug.PrintStack()
}
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
}()
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}