errcode

package
v1.4.64 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 14 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

errcode

Error codes usually include system-level error codes and business-level error codes, consisting of a total of 6 decimal digits, e.g. 200101

Error code structure:

First digit Middle three digits Last two digits
1 is http system-level error
2 is http business-level error
3 is grpc system-level error
4 is grpc system-level error
Table or module number, range 1~1000 Custom number, range 1~100

Error code ranges:

Service Type System-level Error Code Range Business-level Error Code Range
http 100000 ~ 200000 200000 ~ 300000
grpc 300000 ~ 400000 400000 ~ 500000

Example of use

Example of http error code usage

Web services created based on SQL, use the following error code:

    import "github.com/18721889353/sunshine/pkg/gin/response"

    // return error
    response.Error(c, ecode.InvalidParams)
    // rewrite error messages
    response.Error(c, ecode.InvalidParams.RewriteMsg("custom error message"))

    // convert error code to standard http status code
    response.Out(c, ecode.InvalidParams)
    // convert error code to standard http status code, and rewrite error messages
    response.Out(c, ecode.InvalidParams.RewriteMsg("custom error message"))

Web services created based on Protobuf, use the following error code:

    // return error
    return nil, ecode.InvalidParams.Err()
    // rewrite error messages
    return nil, ecode.InvalidParams.Err("custom error message")

    // convert error code to standard http status code
    return nil, ecode.InvalidParams.ErrToHTTP()
    // convert error code to standard http status code, and rewrite error messages
    return nil, ecode.InvalidParams.ErrToHTTP("custom error message")

Example of grpc error code usage

    // return error
    return nil, ecode.StatusInvalidParams.Err()
    // rewrite error messages
    return nil, ecode.StatusInvalidParams.Err("custom error message")

    // convert error code to standard grpc status code
    return nil, ecode.StatusInvalidParams.ToRPCErr()
    // convert error code to standard grpc status code, and rewrite error messages
    return nil, ecode.StatusInvalidParams.ToRPCErr("custom error message")

    // convert error code to standard http status code
    return nil, ecode.StatusInvalidParams.ErrToHTTP()
    // convert error code to standard http status code, and rewrite error messages
    return nil, ecode.StatusInvalidParams.ErrToHTTP("custom error message")

Documentation

Overview

Package errcode 用于定义 HTTP 和 gRPC 错误码,包括系统级别的错误码和业务级别的错误码

Package errcode 提供统一的 HTTP/GRPC 错误码及响应封装。 核心功能:

  • 定义业务错误码与标准 HTTP 状态码的映射关系
  • 提供统一的 JSON 响应格式(code, msg, data)
  • 支持结构体拆包(unwrap),使单切片响应可直接返回数组,简化前端处理
  • 兼容 gRPC 状态码与 HTTP 错误码的转换

Index

Constants

View Source
const ToHTTPCodeLabel = "[standard http code]"

ToHTTPCodeLabel 需要转换为标准 HTTP 状态码的标签

Variables

View Source
var (
	// Success 成功
	// 错误码: 0
	// 描述: 操作成功
	Success = NewError(0, "ok")

	// InvalidParams 无效参数
	// 错误码: 100001
	// 描述: 请求参数无效
	InvalidParams = NewError(100001, "Invalid Parameter")

	// Unauthorized 未授权
	// 错误码: 100002
	// 描述: 用户未被授权访问资源
	Unauthorized = NewError(100002, "Unauthorized")

	// InternalServerError 内部服务器错误
	// 错误码: 100003
	// 描述: 服务器内部发生错误
	InternalServerError = NewError(100003, "Internal Server Error")

	// NotFound 未找到
	// 错误码: 100004
	// 描述: 请求的资源未找到
	NotFound = NewError(100004, "Not Found")

	// Timeout 请求超时
	// 错误码: 100006
	// 描述: 请求超时
	Timeout = NewError(100006, "Request Timeout")

	// TooManyRequests 请求过多
	// 错误码: 100007
	// 描述: 过多的请求
	TooManyRequests = NewError(100007, "Too Many Requests")

	// Forbidden 禁止访问
	// 错误码: 100008
	// 描述: 禁止访问资源
	Forbidden = NewError(100008, "Forbidden")

	// LimitExceed 超过限制
	// 错误码: 100009
	// 描述: 超过了某个限制
	LimitExceed = NewError(100009, "Limit Exceed")

	// DeadlineExceeded 截止时间已过
	// 错误码: 100010
	// 描述: 操作超过了截止时间
	DeadlineExceeded = NewError(100010, "Deadline Exceeded")

	// AccessDenied 访问被拒绝
	// 错误码: 100011
	// 描述: 访问被拒绝
	AccessDenied = NewError(100011, "Access Denied")

	// MethodNotAllowed 方法不允许
	// 错误码: 100012
	// 描述: 请求的方法不被允许
	MethodNotAllowed = NewError(100012, "Method Not Allowed")

	// ServiceUnavailable 服务不可用
	// 错误码: 100013
	// 描述: 服务暂时不可用
	ServiceUnavailable = NewError(100013, "Service Unavailable")

	// Canceled 取消
	// 错误码: 100014
	// 描述: 操作被取消
	Canceled = NewError(100014, "Canceled")

	// Unknown 未知错误
	// 错误码: 100015
	// 描述: 未知错误
	Unknown = NewError(100015, "Unknown")

	// PermissionDenied 权限拒绝
	// 错误码: 100016
	// 描述: 没有足够的权限执行操作
	PermissionDenied = NewError(100016, "Permission Denied")

	// ResourceExhausted 资源耗尽
	// 错误码: 100017
	// 描述: 资源耗尽
	ResourceExhausted = NewError(100017, "Resource Exhausted")

	// FailedPrecondition 前提条件失败
	// 错误码: 100018
	// 描述: 前提条件失败
	FailedPrecondition = NewError(100018, "Failed Precondition")

	// Aborted 中断
	// 错误码: 100019
	// 描述: 操作被中断
	Aborted = NewError(100019, "Aborted")

	// OutOfRange 超出范围
	// 错误码: 100020
	// 描述: 请求的数据超出范围
	OutOfRange = NewError(100020, "Out Of Range")

	// Unimplemented 未实现
	// 错误码: 100021
	// 描述: 功能未实现
	Unimplemented = NewError(100021, "Unimplemented")

	// DataLoss 数据丢失
	// 错误码: 100022
	// 描述: 数据丢失
	DataLoss = NewError(100022, "Data Loss")

	// StatusBadGateway 不良网关
	// 错误码: 100023
	// 描述: 服务器作为网关或代理,从上游服务器收到无效响应
	StatusBadGateway = NewError(100023, "Bad Gateway")

	// AlreadyExists 已存在
	// 错误码: 100005
	// 描述: 资源已存在
	// 注意: 已弃用,建议使用 Conflict 替代
	AlreadyExists = NewError(100005, "Already Exists")

	// Conflict 冲突
	// 错误码: 100409
	// 描述: 请求冲突
	Conflict = NewError(100409, "Conflict")

	// TooEarly 太早
	// 错误码: 100425
	// 描述: 请求太早
	TooEarly = NewError(100425, "Too Early")
)

http系统级别错误码,错误码范围 10000~20000

View Source
var (
	StatusSuccess = NewRPCStatus(0, "ok") // 操作成功

	StatusCanceled            = NewRPCStatus(300001, "Canceled")              // 操作已取消
	StatusUnknown             = NewRPCStatus(300002, "Unknown")               // 未知错误
	StatusInvalidParams       = NewRPCStatus(300003, "Invalid Parameter")     // 参数无效
	StatusDeadlineExceeded    = NewRPCStatus(300004, "Deadline Exceeded")     // 超时
	StatusNotFound            = NewRPCStatus(300005, "Not Found")             // 未找到
	StatusAlreadyExists       = NewRPCStatus(300006, "Already Exists")        // 已存在
	StatusPermissionDenied    = NewRPCStatus(300007, "Permission Denied")     // 权限被拒绝
	StatusResourceExhausted   = NewRPCStatus(300008, "Resource Exhausted")    // 资源耗尽
	StatusFailedPrecondition  = NewRPCStatus(300009, "Failed Precondition")   // 预先条件失败
	StatusAborted             = NewRPCStatus(300010, "Aborted")               // 操作被中止
	StatusOutOfRange          = NewRPCStatus(300011, "Out Of Range")          // 范围外
	StatusUnimplemented       = NewRPCStatus(300012, "Unimplemented")         // 未实现
	StatusInternalServerError = NewRPCStatus(300013, "Internal Server Error") // 内部服务器错误
	StatusServiceUnavailable  = NewRPCStatus(300014, "Service Unavailable")   // 服务不可用
	StatusDataLoss            = NewRPCStatus(300015, "Data Loss")             // 数据丢失
	StatusUnauthorized        = NewRPCStatus(300016, "Unauthorized")          // 未授权

	StatusTimeout          = NewRPCStatus(300017, "Request Timeout")    // 请求超时
	StatusTooManyRequests  = NewRPCStatus(300018, "Too Many Requests")  // 请求过多
	StatusForbidden        = NewRPCStatus(300019, "Forbidden")          // 禁止访问
	StatusLimitExceed      = NewRPCStatus(300020, "Limit Exceed")       // 超出限制
	StatusMethodNotAllowed = NewRPCStatus(300021, "Method Not Allowed") // 方法不允许
	StatusAccessDenied     = NewRPCStatus(300022, "Access Denied")      // 访问被拒绝
	StatusConflict         = NewRPCStatus(300023, "Conflict")           // 冲突
)

rpc system level error code with status prefix, error code range 30000~40000 RPC系统级别错误代码,错误代码范围为30000到40000

View Source
var (
	// SkipResponse 用于中间件或业务逻辑中跳过后续响应处理(如已自行处理)
	//nolint:revive // 保留命名以兼容已有代码
	SkipResponse = errors.New("skip response")
)

Functions

func GetErrorCode added in v1.0.5

func GetErrorCode(err error) int

GetErrorCode 从 HTTP 调用返回的错误中获取错误码

func GetStatusCode added in v1.0.5

func GetStatusCode(err error) codes.Code

GetStatusCode 从 gRPC 调用返回的错误中获取状态代码

func HCode

func HCode(num int) int

HCode 根据传入的数字生成一个介于 200000 和 300000 之间的错误码

该函数用于生成 HTTP 服务级别的错误码,错误码前缀为 Err,例如:

var (

ErrUserCreate = NewError(HCode(1)+1, "failed to create user")   // 200101
ErrUserDelete = NewError(HCode(1)+2, "failed to delete user")   // 200102
ErrUserUpdate = NewError(HCode(1)+3, "failed to update user")   // 200103
ErrUserGet    = NewError(HCode(1)+4, "failed to get user details") // 200104

)

参数: - num: 一个整数,表示错误码的子类别编号,范围必须在 1 到 999 之间。

返回值: - 一个整数,表示生成的错误码。

异常: - 如果 num 不在 1 到 999 的范围内,函数会 panic 并抛出错误信息 "num range must be between 0 to 1000"。

func ListGRPCErrCodes

func ListGRPCErrCodes(w http.ResponseWriter, _ *http.Request)

ListGRPCErrCodes 列出所有 gRPC 错误代码,HTTP 处理函数

func RCode

func RCode(num int) codes.Code

RCode 生成一个介于 400000 和 500000 之间的错误代码

该函数用于生成服务级别的错误代码,根据传入的数字生成相应的错误代码。 例如:

var (
	StatusUserCreate = NewRPCStatus(RCode(1)+1, "failed to create user")		// 400101
	StatusUserDelete = NewRPCStatus(RCode(1)+2, "failed to delete user")		// 400102
	StatusUserUpdate = NewRPCStatus(RCode(1)+3, "failed to update user")		// 400103
	StatusUserGet    = NewRPCStatus(RCode(1)+4, "failed to get user details")	// 400104
)

参数: - num: 生成错误代码的基础数字,必须在 1 到 999 之间。

返回: - codes.Code: 生成的 gRPC 错误代码。

func Respond added in v1.4.55

func Respond(c *gin.Context, respStatus int, code any, msg string, data any)

Respond 按全局 ResponseFormat 输出响应(字段名/空数据规范化实时生效),code 原样保留类型, 供 pkg/gin/response 等适配层复用统一格式,避免维护第二套不读配置的出口

func SetResponseFormat added in v1.4.55

func SetResponseFormat(f ResponseFormat)

SetResponseFormat 设置全局响应格式,重复调用以最后一次为准(热更新场景由配置层重新调用)

func ShowConfig

func ShowConfig(jsonData []byte) func(w http.ResponseWriter, _ *http.Request)

ShowConfig 显示配置信息 @Summary 显示配置信息 @Description 显示配置信息 @Tags system @Accept json @Produce json @Router /config [get]

Types

type Detail

type Detail struct {
	// contains filtered or unexported fields
}

Detail 用于存储错误详情的键值对

func Any

func Any(key string, val interface{}) Detail

Any 创建一个 Detail 对象

func (*Detail) String

func (d *Detail) String() string

String 返回 Detail 的字符串表示形式

type ErrInfo

type ErrInfo struct {
	Code int    `json:"code"` // 错误代码
	Msg  string `json:"msg"`  // 错误消息
}

ErrInfo 用于存储错误信息

func ListHTTPErrCodes

func ListHTTPErrCodes() []ErrInfo

ListHTTPErrCodes 列出 HTTP 错误码

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error 错误结构体

func NewError

func NewError(code int, msg string, details ...string) *Error

NewError 创建一个新的错误消息

func ParseError

func ParseError(err error) *Error

ParseError 从错误消息中解析出错误码

func ToHTTPErr

func ToHTTPErr(st *status.Status) *Error

ToHTTPErr 将 gRPC 状态转换为对应的 *Error,适用于业务错误码与 gRPC 码的桥接

func (*Error) Code

func (e *Error) Code() int

Code 获取错误码

func (*Error) Details

func (e *Error) Details() []string

Details 获取错误详情

func (*Error) Err

func (e *Error) Err(msg ...string) error

Err 转换为标准错误 如果有参数 'msg',则会替换原始消息

func (*Error) ErrToHTTP

func (e *Error) ErrToHTTP(msg ...string) error

ErrToHTTP 转换为标准错误并添加 ToHTTPCodeLabel 到错误消息 如果需要转换为标准 HTTP 状态码,可以使用此方法 提示:可以调用 GetErrorCode 函数获取标准 HTTP 状态码

func (*Error) Msg

func (e *Error) Msg() string

Msg 获取错误消息

func (*Error) NeedHTTPCode

func (e *Error) NeedHTTPCode() bool

NeedHTTPCode 是否需要转换为标准 HTTP 状态码

func (*Error) RewriteMsg added in v1.0.43

func (e *Error) RewriteMsg(msg string) *Error

RewriteMsg 重写错误消息

func (*Error) ToHTTPCode

func (e *Error) ToHTTPCode() int

ToHTTPCode 转换为 HTTP 状态码

func (*Error) WithDetails

func (e *Error) WithDetails(details ...string) *Error

WithDetails 添加错误详情

func (*Error) WithOutMsg

func (e *Error) WithOutMsg(msg string) *Error

WithOutMsg 输出错误消息 已弃用:请使用 RewriteMsg 替代

func (*Error) WithOutMsgI18n

func (e *Error) WithOutMsgI18n(langMsg map[int]map[string]string, lang string) *Error

WithOutMsgI18n 输出国际化错误消息 langMsg 示例:

map[int]map[string]string{
		20010: {
			"en-US": "login failed",
			"zh-CN": "登录失败",
		},
	}

lang BCP 47 代码 https://learn.microsoft.com/en-us/openspecs/office_standards/ms-oe376/6c085406-a698-4e12-9d4d-c3b0ee3dbc4a

type RPCStatus

type RPCStatus struct {
	// contains filtered or unexported fields
}

RPCStatus 用于封装 gRPC 状态

func NewRPCStatus

func NewRPCStatus(code codes.Code, msg string) *RPCStatus

NewRPCStatus 创建一个新的 gRPC 状态

func (*RPCStatus) Code

func (s *RPCStatus) Code() codes.Code

Code 获取 gRPC 状态代码

func (*RPCStatus) Err

func (s *RPCStatus) Err(desc ...string) error

Err 返回一个 gRPC 错误 如果有参数 'desc',则替换原始消息

func (*RPCStatus) ErrToHTTP

func (s *RPCStatus) ErrToHTTP(desc ...string) error

ErrToHTTP 将 gRPC 错误转换为标准 HTTP 错误,并添加 ToHTTPCodeLabel 标签 通常用于 HTTP 调用 gRPC API 时 如果有参数 'desc',则替换原始消息

func (*RPCStatus) Msg

func (s *RPCStatus) Msg() string

Msg 获取 gRPC 状态消息

func (*RPCStatus) ToRPCCode

func (s *RPCStatus) ToRPCCode() codes.Code

ToRPCCode 将当前状态转换为标准的 gRPC 错误代码

func (*RPCStatus) ToRPCErr

func (s *RPCStatus) ToRPCErr(desc ...string) error

ToRPCErr 将当前状态转换为标准的 gRPC 错误 如果有参数 'desc',则替换原始消息

type ResponseFormat added in v1.4.55

type ResponseFormat struct {
	CodeField           string // 响应体 code 字段名,空则默认 "code",可配为 status/resultCode 等
	MsgField            string // 响应体 msg 字段名,空则回退 isMessage 旧逻辑(msg/message),可配为 errorInfo 等
	DataField           string // 响应体 data 字段名,空则默认 "data",可配为 result/payload 等
	SuccessCode         any    // 成功响应码,空则默认数字 0;类型跟随配置写法原样透传:YAML 不带引号(0)输出 JSON 数字,带引号("0")输出 JSON 字符串
	SuccessMsg          string // 成功响应提示,空则默认 "ok"
	DoingMsg            string // 业务自定义码(非成功码)时的提示,空则回落 SuccessMsg,仅 ExtractCustomCode=true 时生效
	ParamErrorCode      any    // 参数错误响应码,空则使用 InvalidParams 错误码(数字,类型透传规则同 SuccessCode)
	ParamErrorMsg       string // 参数错误响应提示,空则使用 InvalidParams 提示
	ExtractCustomCode   bool   // 是否从 data 中提取 CustomCode(或 map 的 code 键)作为业务响应码,并从 data 中剥离该字段
	NilDataAsEmptyArray bool   // nil/空 data 序列化为 [] 而非 {}
}

ResponseFormat 全局响应格式配置,零值即内置默认行为; 由各应用的配置层(如 internal/config 的 response 段)在启动与热更新时通过 SetResponseFormat 注入, 每次响应时实时读取,天然支持热更新

type Responser

type Responser interface {
	// Success 返回成功响应,code=0, msg="ok",data 自动拆包;
	// 响应体字段名、默认 code/msg 内容、业务码提取模式均可通过 SetResponseFormat 注入(配合应用配置 response 段),无需替换实现
	Success(ctx *gin.Context, data any)
	// ParamError 参数错误响应(通常由 validation 校验失败触发)
	ParamError(ctx *gin.Context, err error)
	// Error 错误响应,根据错误类型自动切换 HTTP/RPC 处理,返回布尔值表示是否已处理
	Error(ctx *gin.Context, err error) bool
}

Responser 定义统一响应接口,所有响应实现必须遵循此接口

func NewResponser

func NewResponser(isMessage, isFromRPC bool, httpErrors []*Error, rpcStatus []*RPCStatus) Responser

NewResponser 创建新的响应器实例,传入配置选项

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL