84 lines
1.5 KiB
Go
84 lines
1.5 KiB
Go
package e
|
|
|
|
import "github.com/goccy/go-json"
|
|
|
|
const (
|
|
UnKnow = 1
|
|
ValidErr = 1000
|
|
DbErr = 2020
|
|
IllegalPhone = 2001
|
|
NoAuth = 401
|
|
NoUser = 2003
|
|
ExistingUserName = 2004
|
|
UnmarshalReqErr = 3000
|
|
Ordinary = 6666
|
|
)
|
|
|
|
func init() {
|
|
m := map[int]string{
|
|
UnKnow: "未定义错误",
|
|
ValidErr: "无效的请求参数",
|
|
DbErr: "数据库错误",
|
|
IllegalPhone: "请输入正确的手机号码",
|
|
NoAuth: "未授权",
|
|
NoUser: "未找到对应用户",
|
|
ExistingUserName: "已经存在的用户",
|
|
UnmarshalReqErr: "参数类型错误",
|
|
}
|
|
|
|
errMap[UnKnow] = &ApiError{
|
|
Status: 500,
|
|
Code: UnKnow,
|
|
Message: "未定义错误",
|
|
}
|
|
|
|
for k, v := range m {
|
|
errMap[k] = &ApiError{
|
|
Status: 200,
|
|
Code: k,
|
|
Message: v,
|
|
}
|
|
}
|
|
}
|
|
|
|
var errMap = map[int]*ApiError{}
|
|
|
|
func NewCode(code int) *ApiError {
|
|
if e, ok := errMap[code]; ok {
|
|
return e
|
|
}
|
|
return errMap[UnKnow]
|
|
}
|
|
func NewString(msg string) *ApiError {
|
|
return &ApiError{
|
|
Status: 200,
|
|
Code: Ordinary,
|
|
Message: msg,
|
|
}
|
|
}
|
|
func newErr(err *ApiError) *ApiError {
|
|
return &(*err)
|
|
}
|
|
func NewValidErr(err error) error {
|
|
if _, ok := err.(*json.UnmarshalTypeError); ok {
|
|
return newErr(errMap[UnmarshalReqErr])
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (e *ApiError) Set(msg string) *ApiError {
|
|
r := *e
|
|
r.Message = msg
|
|
return &r
|
|
}
|
|
|
|
type ApiError struct {
|
|
Status int `json:"-"`
|
|
Code int `json:"code"`
|
|
Message string `json:"msg"`
|
|
}
|
|
|
|
func (e *ApiError) Error() string {
|
|
return e.Message
|
|
}
|