forked from labstack/echo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover.go
66 lines (58 loc) · 1.63 KB
/
recover.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package middleware
import (
"fmt"
"runtime"
"github.com/labstack/echo"
"github.com/labstack/gommon/color"
)
type (
// RecoverConfig defines config for recover middleware.
RecoverConfig struct {
// StackSize is the stack size to be printed.
StackSize int
// StackAll is flag to format stack traces of all other goroutines into
// buffer after the trace for the current goroutine, or not. Default is true.
StackAll bool
// PrintStack is the flag to print stack or not. Default is true.
PrintStack bool
}
)
var (
// DefaultRecoverConfig is the default recover middleware config.
DefaultRecoverConfig = RecoverConfig{
StackSize: 4 << 10, // 4 KB
StackAll: true,
PrintStack: true,
}
)
// Recover returns a middleware which recovers from panics anywhere in the chain
// and handles the control to the centralized HTTPErrorHandler.
func Recover() echo.MiddlewareFunc {
return RecoverFromConfig(DefaultRecoverConfig)
}
// RecoverFromConfig returns a recover middleware from config.
// See `Recover()`.
func RecoverFromConfig(config RecoverConfig) echo.MiddlewareFunc {
return func(next echo.Handler) echo.Handler {
return echo.HandlerFunc(func(c echo.Context) error {
defer func() {
if r := recover(); r != nil {
var err error
switch r := r.(type) {
case error:
err = r
default:
err = fmt.Errorf("%v", r)
}
stack := make([]byte, config.StackSize)
length := runtime.Stack(stack, config.StackAll)
if config.PrintStack {
c.Logger().Printf("[%s] %s %s", color.Red("PANIC RECOVER"), err, stack[:length])
}
c.Error(err)
}
}()
return next.Handle(c)
})
}
}