forked from storezhang/echox
-
Notifications
You must be signed in to change notification settings - Fork 1
/
error_handler.go
49 lines (43 loc) · 1.19 KB
/
error_handler.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
package echox
import (
`net/http`
`github.com/dgrijalva/jwt-go`
`github.com/go-playground/validator/v10`
`github.com/labstack/echo/v4`
`github.com/storezhang/gox`
`github.com/storezhang/validatorx`
)
type errorHandler func(err error, ctx echo.Context)
func errorHandlerFunc(err error, ctx echo.Context) {
rsp := response{}
statusCode := http.StatusInternalServerError
switch e := err.(type) {
case *echo.HTTPError:
statusCode = e.Code
rsp.ErrorCode = 9902
rsp.Message = "处理请求失败"
if nil != e.Internal {
rsp.Data = e.Internal.Error()
}
case *jwt.ValidationError:
statusCode = http.StatusUnauthorized
rsp.ErrorCode = 9904
rsp.Message = "登录失效,请重新登录"
rsp.Data = e.Error()
case validator.ValidationErrors:
statusCode = http.StatusBadRequest
lang := ctx.Request().Header.Get(gox.HeaderAcceptLanguage)
rsp.ErrorCode = 9901
rsp.Message = "数据验证错误"
rsp.Data = validatorx.I18n(lang, e)
case *gox.CodeError:
rsp.ErrorCode = int(e.ToErrorCode())
rsp.Message = e.ToMessage()
rsp.Data = e.ToData()
default:
rsp.ErrorCode = 9903
rsp.Message = "服务器内部错误"
rsp.Data = err.Error()
}
_ = ctx.JSON(statusCode, rsp)
}