-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecover.go
53 lines (45 loc) · 864 Bytes
/
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
package lama
import (
"github.com/gookit/validate"
"github.com/kataras/iris/v12/context"
"time"
)
type Recover struct {
debug bool
}
func (s *Recover) Init(app IRISApp) error {
app.UseGlobal(func(ctx *context.Context) {
defer func() {
if err := recover(); err != nil {
if ctx.IsStopped() { // handled by other middleware.
return
}
var code int
var msg string
ret := map[string]any{
"state": false,
"time": time.Now().Unix(),
}
switch e := err.(type) {
case string:
code = 400
msg = e
case validate.Errors:
code = 400
msg = e.One()
default:
code = 500
msg = "Server internal error"
if s.debug {
// todo 优化
msg = err.(error).Error()
}
}
ret["msg"] = msg
ctx.StopWithJSON(code, ret)
}
}()
ctx.Next()
})
return nil
}