-
Notifications
You must be signed in to change notification settings - Fork 1
/
panics.go
45 lines (34 loc) · 1.08 KB
/
panics.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
package mid
import (
"context"
"fmt"
"net/http"
"runtime/debug"
"github.com/AhmedShaef/wakt/business/sys/metrics"
"github.com/AhmedShaef/wakt/foundation/web"
)
// Panics recovers from panics and converts the panic to an error, so it is
// reported in Metrics and handled in Errors.
func Panics() web.Middleware {
// This is the actual middleware function to be executed.
m := func(handler web.Handler) web.Handler {
// Create the handler that will be attached in the middleware chain.
h := func(ctx context.Context, w http.ResponseWriter, r *http.Request) (err error) {
// Defer a function to recover from a panic and set to return err
// variable after the fact.
defer func() {
if rec := recover(); rec != nil {
// Stack trace will be provided.
trace := debug.Stack()
err = fmt.Errorf("PANIC [%v] TRACE[%s]", rec, string(trace))
// Updates the metrics stored in the context.
metrics.AddPanics(ctx)
}
}()
// Call the next handler and set its return value in the err variable.
return handler(ctx, w, r)
}
return h
}
return m
}