-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy patherror.go
69 lines (56 loc) · 1.13 KB
/
error.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
67
68
69
package twig
import (
"fmt"
"net/http"
)
// HttpError 封装一个HttpError
type HttpError struct {
Code int
Msg interface{}
Internal error
}
func NewHttpError(code int, msg ...interface{}) *HttpError {
e := &HttpError{
Code: code,
Msg: http.StatusText(code),
}
if len(msg) > 0 {
e.Msg = msg[0]
}
return e
}
func (e *HttpError) Error() string {
return fmt.Sprintf("code = %d, msg = %v", e.Code, e.Msg)
}
func (e *HttpError) SetInternal(err error) *HttpError {
e.Internal = err
return e
}
type HttpErrorHandler func(error, Ctx)
// 默认的错误处理
var DefaultHttpErrorHandler = func(err error, c Ctx) {
var code int = http.StatusInternalServerError
var msg interface{}
if e, ok := err.(*HttpError); ok {
code = e.Code
msg = e.Msg
if e.Internal != nil {
err = fmt.Errorf("%v, %v", err, e.Internal)
}
} else {
msg = http.StatusText(code)
}
if m, ok := msg.(string); ok {
msg = map[string]string{"msg": m}
}
if !c.Resp().Committed {
if c.Req().Method == http.MethodHead {
err = c.NoContent()
} else {
err = c.JSON(code, msg)
}
if err != nil {
c.Logger().Println(err)
}
}
}