Documentation
¶
Index ¶
- func GRPCStreamServerInterceptor(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, ...) error
- func GRPCUnaryServerInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, ...) (any, error)
- func HTTPMiddlewareErrorHandler(next http.Handler) http.Handler
- func Register(code Code, httpStatus int, grpcCode uint32, defaultMsg string)
- func SetError(ctx context.Context, err error)
- func ToGRPC(s *Status) error
- func WriteHTTP(w http.ResponseWriter, s *Status)
- type Code
- type Detail
- type ErrorInfo
- type FieldViolation
- type QuotaViolation
- type ResourceInfo
- type RetryInfo
- type Status
- func Conflict(msg string) *Status
- func Forbidden(msg string) *Status
- func FromError(err error) (*Status, bool)
- func FromGRPCError(err error) (*Status, bool)
- func Internal(msg string) *Status
- func InvalidArgument(msg string) *Status
- func New(code Code, message string) *Status
- func Newf(code Code, format string, args ...any) *Status
- func NotFound(msg string) *Status
- func TooManyRequests(msg string) *Status
- func Unauthenticated(msg string) *Status
- func Unavailable(msg string) *Status
- func Unimplemented(msg string) *Status
- func (s *Status) Cause() error
- func (s *Status) Code() Code
- func (s *Status) Details() []Detail
- func (s *Status) Error() string
- func (s *Status) Is(target error) bool
- func (s *Status) Message() string
- func (s *Status) Unwrap() error
- func (s *Status) WithCause(err error) *Status
- func (s *Status) WithDetail(d Detail) *Status
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GRPCStreamServerInterceptor ¶
func GRPCStreamServerInterceptor(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error
GRPCStreamServerInterceptor 与 GRPCUnaryServerInterceptor 对应的 stream 版本。
func GRPCUnaryServerInterceptor ¶
func GRPCUnaryServerInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error)
GRPCUnaryServerInterceptor 将 handler 返回的 *Status 自动转换为 gRPC status error。 业务代码直接 return errors.NotFound("user not found"),无需手动调 ToGRPC。
func HTTPMiddlewareErrorHandler ¶
HTTPMiddlewareErrorHandler 返回一个 HTTP 中间件,将 handler 产生的 *Status 错误 转换为结构化 JSON 响应。handler 通过 ctx 中的 errorSink 写入错误。
使用场景:handler 无法直接返回 error(net/http 签名限制), 可通过 SetError(ctx, err) 写入,中间件统一处理。
func MyHandler(w http.ResponseWriter, r *http.Request) {
user, err := svc.GetUser(r.Context(), id)
if err != nil {
errors.SetError(r.Context(), err)
return
}
json.NewEncoder(w).Encode(user)
}
func Register ¶
Register 注册一个业务码的映射关系。 框架内置码在 predefined.go 中通过 init() 注册;业务方在自己的 init() 中调用。 重复注册同一个 Code 会 panic,防止无声覆盖。
func SetError ¶
SetError 将错误写入 ctx 的 errorSink,供 HTTPMiddlewareErrorHandler 读取。 若 ctx 没有 sink(未经过 HTTPMiddlewareErrorHandler 包装),调用是无操作。
func WriteHTTP ¶
func WriteHTTP(w http.ResponseWriter, s *Status)
WriteHTTP 将 *Status 序列化为 JSON 写入 http.ResponseWriter。 Content-Type 固定为 application/json。
Types ¶
type Code ¶
type Code int32
Code 业务错误码,32 位整数。 框架预留 1-999,业务自定义从 1000 起。 推荐约定:高位表示模块,低位表示具体错误,例如 10404 = 通用模块-不存在。
const ( CodeOK Code = 0 // 4xx 客户端错误 CodeInvalidArgument Code = 400 // 参数非法 CodeUnauthenticated Code = 401 // 未认证 CodeForbidden Code = 403 // 无权限 CodeNotFound Code = 404 // 资源不存在 CodeConflict Code = 409 // 资源冲突/已存在 CodeTooManyRequests Code = 429 // 请求过频 CodeFailedPrecondition Code = 412 // 前置条件不满足 // 5xx 服务端错误 CodeInternal Code = 500 // 内部错误 CodeUnimplemented Code = 501 // 未实现 CodeDeadline Code = 504 // 超时 )
框架预定义业务码(1–999 保留给框架)
func (Code) HTTPStatus ¶
HTTPStatus 返回该 Code 对应的 HTTP status code;未注册时返回 500。
type Detail ¶
type Detail interface {
// contains filtered or unexported methods
}
Detail 是结构化错误详情的接口。 所有内置详情类型和业务自定义详情类型都实现它。
type ErrorInfo ¶
type ErrorInfo struct {
Reason string // 错误原因标识,如 "USER_NOT_FOUND",建议全大写下划线
Domain string // 服务域,如 "user-service"
Metadata map[string]string // 扩展 KV,如 {"user_id": "123"}
}
ErrorInfo 携带错误的机器可读原因和元数据,适合在微服务间传递结构化错误原因。
type FieldViolation ¶
type FieldViolation struct {
Field string // 字段名,如 "user.email"
Description string // 描述,如 "must be a valid email address"
}
FieldViolation 字段校验失败,适用于参数校验错误(400)。 一个 Status 可以携带多个 FieldViolation,每个对应一个非法字段。
type QuotaViolation ¶
type QuotaViolation struct {
Subject string // 配额主体,如 "project/my-project/quota/read-requests-per-day"
Description string // 如 "daily read quota exceeded"
}
QuotaViolation 配额超限,适用于 429 场景,描述哪个配额被超限。
type ResourceInfo ¶
type ResourceInfo struct {
ResourceType string // 资源类型,如 "User"、"Order"
Name string // 资源标识,如 id 或 name
Description string // 可选的补充说明
}
ResourceInfo 描述操作涉及的资源,适用于 NotFound(404)或 AlreadyExists(409)。
type Status ¶
type Status struct {
// contains filtered or unexported fields
}
Status 是框架统一的业务错误类型。 实现标准 error 接口,可直接从 HTTP handler 或 gRPC handler 返回。
HTTP recovery 中间件和 gRPC 拦截器会识别 *Status, 根据 Code 的注册映射自动转换为正确的 HTTP status code 或 gRPC status code。 普通 error 仍然兜底返回 500 / codes.Internal,向后兼容。
func FromError ¶
FromError 从任意 error 中提取 *Status。 若 err 本身或其链路中包含 *Status,返回 (status, true);否则返回 (nil, false)。
func FromGRPCError ¶
FromGRPCError 尝试将 gRPC status error 还原为 *Status。 若输入不是 gRPC status error,返回 (nil, false)。
func InvalidArgument ¶
func TooManyRequests ¶
func Unauthenticated ¶
func Unavailable ¶
func Unimplemented ¶
func (*Status) Is ¶
Is 让 errors.Is 能够按 Code 匹配。
target := errors.New(ErrNotFound, "") errors.Is(err, target) // true 当 err 的 Code == ErrNotFound
func (*Status) WithDetail ¶
WithDetail 追加一个结构化详情,返回自身(链式调用)。