hyapp-server/pkg/xerr/errors.go
2026-04-25 01:18:30 +08:00

56 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package xerr
import "fmt"
// Code 用稳定错误码表达跨层失败语义。
// 这里不直接暴露 gRPC code是为了让领域层不依赖传输层。
type Code string
const (
// InvalidArgument 表示请求本身不满足领域约束。
InvalidArgument Code = "invalid_argument"
// NotFound 表示目标房间或目标用户等实体不存在。
NotFound Code = "not_found"
// Conflict 表示版本、幂等或所有权冲突。
Conflict Code = "conflict"
// PermissionDenied 表示鉴权通过但权限不够。
PermissionDenied Code = "permission_denied"
// Unavailable 表示依赖不可用或实例恢复失败。
Unavailable Code = "unavailable"
// Internal 表示当前层无法对外暴露更精确语义的内部错误。
Internal Code = "internal"
)
// Error 是跨服务内部统一使用的领域错误。
type Error struct {
Code Code
Message string
}
// Error 实现标准 error 接口。
func (e *Error) Error() string {
return fmt.Sprintf("%s: %s", e.Code, e.Message)
}
// New 构造统一领域错误。
func New(code Code, message string) error {
return &Error{
Code: code,
Message: message,
}
}
// CodeOf 负责安全提取错误码。
func CodeOf(err error) Code {
if err == nil {
return ""
}
typed, ok := err.(*Error)
if !ok {
return Internal
}
return typed.Code
}