Files
zt-online-game-backend/pkg/errcode/errcode.go
T
zhengchiliu ff9add8655 补齐 HTTP 层:实现用户模块、路由与中间件接线、COS 上传及优雅启动
- 新增用户与上传错误码文件及 Recovery 中间件
- 修复 router.go 导入与中间件链,注册用户路由并补 handler 错误码导入
- 补充用户状态常量与 UserGetByWechatOpenID 查询,修订刷新令牌 dto
- 移除 upload 包 OTel 调用,新增 FileUploadCos 上传封装
- 实现 UserService 微信登录/刷新令牌/我的信息/改资料/上传头像
- 裁剪 main.go 配置段并移除 OTel 桥接,补启动与优雅退出
- 新增 configs 示例配置、global 配置结构及 go.mod 依赖
2026-09-27 15:02:01 +08:00

78 lines
1.9 KiB
Go

package errcode
import (
"fmt"
"net/http"
)
// Error 业务错误
type Error struct {
code int
msg string
details []string
}
// codes 用于注册时去重检查
var codes = map[int]string{}
// NewError 注册并创建一个错误码
func NewError(code int, msg string) *Error {
if _, exists := codes[code]; exists {
panic(fmt.Sprintf("error code %d already exists, please change", code))
}
codes[code] = msg
return &Error{code: code, msg: msg}
}
func (e *Error) Error() string {
return fmt.Sprintf("error code: %d, msg: %s", e.code, e.msg)
}
func (e *Error) Code() int { return e.code }
func (e *Error) Msg() string { return e.msg }
func (e *Error) Details() []string { return e.details }
func (e *Error) Msgf(args ...interface{}) string {
return fmt.Sprintf(e.msg, args...)
}
// WithDetails 附加详细信息(返回副本)
func (e *Error) WithDetails(details ...string) *Error {
newError := *e
newError.details = append(newError.details, details...)
return &newError
}
// StatusCode 业务码 → HTTP 状态码
// 仅对少数特殊错误返回非 200,其余统一 200,由前端按业务 code 处理
func (e *Error) StatusCode() int {
switch e.code {
case Success.Code():
return http.StatusOK
// 鉴权类返回 401,便于前端拦截器统一处理跳转登录
case Unauthorized.Code(),
UnauthorizedTokenError.Code(),
UnauthorizedTokenTimeout.Code(),
UnauthorizedTokenMissing.Code():
return http.StatusUnauthorized
// 越权/无权限返回 403,便于网关与审计识别越权事件
case Forbidden.Code():
return http.StatusForbidden
// 限流返回 429,便于网关识别限流事件
case TooManyRequests.Code():
return http.StatusTooManyRequests
// 系统错误返回 500,便于运维监控告警
case ServerError.Code(),
DatabaseError.Code(),
CacheError.Code(),
RPCError.Code(),
UnknownError.Code():
return http.StatusInternalServerError
}
return http.StatusOK
}