err_handler.go
1.1 KB
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 xerr
import (
"context"
"github.com/samber/lo"
"github.com/zeromicro/go-zero/core/logx"
"net/http"
)
func ErrorHandlerCtx(ctx context.Context, err error) (int, any) {
//错误返回
var (
errCode = ServerCommonError
errMsg = ""
)
// 自定义错误类型
if codeError, ok := err.(*CodeError); ok {
errCode = codeError.GetErrCode()
errMsg = codeError.GetErrMsg()
}
logx.WithContext(ctx).Errorf("【ERROR-HANDLER】 : %+v ", err)
response := Error(int(errCode), lo.Ternary(errMsg != "", errMsg, MapErrMsg(errCode)))
response.Error = err.Error()
return http.StatusOK, response
}
func OkHandlerCtx(ctx context.Context, a any) any {
return Success(a)
}
func Success(data interface{}) *ResponseSuccessBean {
return &ResponseSuccessBean{Code: 0, Msg: "OK", Data: data}
}
type ResponseSuccessBean struct {
Code uint32 `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
type ResponseErrorBean struct {
Code int `json:"code"`
Msg string `json:"msg"`
Error string `json:"err"`
}
func Error(errCode int, errMsg string) *ResponseErrorBean {
return &ResponseErrorBean{Code: errCode, Msg: errMsg}
}