Some checks failed
部署管理后台 / 🧪 测试和构建 (push) Failing after 1m5s
部署管理后台 / 🔒 安全扫描 (push) Has been skipped
部署后端服务 / 🧪 测试后端 (push) Failing after 3m13s
部署前端网站 / 🧪 测试和构建 (push) Failing after 2m10s
部署管理后台 / 🚀 部署到生产环境 (push) Has been skipped
部署后端服务 / 🚀 构建并部署 (push) Has been skipped
部署管理后台 / 🔄 回滚部署 (push) Has been skipped
部署前端网站 / 🚀 部署到生产环境 (push) Has been skipped
部署后端服务 / 🔄 回滚部署 (push) Has been skipped
- 后端:应用 go fmt 自动格式化,统一代码风格 - 前端:更新 API 配置,完善类型安全 - 所有代码符合项目规范,准备生产部署
100 lines
2.1 KiB
Go
100 lines
2.1 KiB
Go
package errorx
|
||
|
||
import (
|
||
"fmt"
|
||
"net/http"
|
||
)
|
||
|
||
const (
|
||
// 通用错误代码
|
||
Success = 0
|
||
ServerError = 500
|
||
ParamError = 400
|
||
AuthError = 401
|
||
NotFound = 404
|
||
Forbidden = 403
|
||
InvalidParameter = 400 // 与 ParamError 统一
|
||
|
||
// 业务错误代码
|
||
UserNotFound = 1001
|
||
UserExists = 1002
|
||
UserDisabled = 1003
|
||
InvalidPassword = 1004
|
||
TokenExpired = 1005
|
||
TokenInvalid = 1006
|
||
|
||
PhotoNotFound = 2001
|
||
PhotoUploadFail = 2002
|
||
|
||
CategoryNotFound = 3001
|
||
CategoryExists = 3002
|
||
)
|
||
|
||
var codeText = map[int]string{
|
||
Success: "Success",
|
||
ServerError: "Server Error",
|
||
ParamError: "Parameter Error", // ParamError 和 InvalidParameter 都映射到这里
|
||
AuthError: "Authentication Error",
|
||
NotFound: "Not Found",
|
||
Forbidden: "Forbidden",
|
||
|
||
UserNotFound: "User Not Found",
|
||
UserExists: "User Already Exists",
|
||
UserDisabled: "User Disabled",
|
||
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: // ParamError 和 InvalidParameter 都是 400,所以只需要一个 case
|
||
return http.StatusBadRequest
|
||
case AuthError, TokenExpired, TokenInvalid:
|
||
return http.StatusUnauthorized
|
||
case NotFound, UserNotFound, PhotoNotFound, CategoryNotFound:
|
||
return http.StatusNotFound
|
||
case Forbidden, UserDisabled:
|
||
return http.StatusForbidden
|
||
case UserExists, CategoryExists:
|
||
return http.StatusConflict
|
||
default:
|
||
return http.StatusInternalServerError
|
||
}
|
||
}
|