package errorx import ( "fmt" "net/http" ) const ( // 通用错误代码 Success = 0 ServerError = 500 ParamError = 400 AuthError = 401 NotFound = 404 Forbidden = 403 // 业务错误代码 UserNotFound = 1001 UserExists = 1002 InvalidPassword = 1003 TokenExpired = 1004 TokenInvalid = 1005 PhotoNotFound = 2001 PhotoUploadFail = 2002 CategoryNotFound = 3001 CategoryExists = 3002 ) var codeText = map[int]string{ Success: "Success", ServerError: "Server Error", ParamError: "Parameter Error", AuthError: "Authentication Error", NotFound: "Not Found", Forbidden: "Forbidden", UserNotFound: "User Not Found", UserExists: "User Already Exists", InvalidPassword: "Invalid Password", TokenExpired: "Token Expired", TokenInvalid: "Token Invalid", PhotoNotFound: "Photo Not Found", PhotoUploadFail: "Photo Upload Failed", CategoryNotFound: "Category Not Found", CategoryExists: "Category Already Exists", } type CodeError struct { Code int `json:"code"` Msg string `json:"msg"` } func (e *CodeError) Error() string { return fmt.Sprintf("Code: %d, Msg: %s", e.Code, e.Msg) } func New(code int, msg string) *CodeError { return &CodeError{ Code: code, Msg: msg, } } func NewWithCode(code int) *CodeError { msg, ok := codeText[code] if !ok { msg = codeText[ServerError] } return &CodeError{ Code: code, Msg: msg, } } func GetHttpStatus(code int) int { switch code { case Success: return http.StatusOK case ParamError: return http.StatusBadRequest case AuthError, TokenExpired, TokenInvalid: return http.StatusUnauthorized case NotFound, UserNotFound, PhotoNotFound, CategoryNotFound: return http.StatusNotFound case Forbidden: return http.StatusForbidden case UserExists, CategoryExists: return http.StatusConflict default: return http.StatusInternalServerError } }