errors

package
v0.1.9 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultFactory = NewErrorFactory("croupier")

全局默认错误工厂

Functions

func AddCustomErrorConfig

func AddCustomErrorConfig(config ErrorConfig)

AddCustomErrorConfig 添加自定义错误配置

func GetAllErrorConfigs

func GetAllErrorConfigs() map[ErrorCode]ErrorConfig

GetAllErrorConfigs 获取所有错误配置

func GetHTTPStatusCode

func GetHTTPStatusCode(code ErrorCode) int

GetHTTPStatusCode 根据错误码获取HTTP状态码

func IsRetryable

func IsRetryable(code ErrorCode) bool

GetRetryable 判断错误是否可重试

func IsUserError

func IsUserError(code ErrorCode) bool

GetUserError 判断是否为用户错误

func ResponseMiddleware

func ResponseMiddleware(next http.Handler) http.Handler

ResponseMiddleware injects request id and start time into context and response headers.

func SendError

func SendError(w http.ResponseWriter, r *http.Request, err error)

SendError 发送错误响应

func SendPaginated

func SendPaginated(w http.ResponseWriter, r *http.Request, data interface{}, pagination *Pagination)

SendPaginated 发送分页响应

func SendPaginatedWithMetadata

func SendPaginatedWithMetadata(w http.ResponseWriter, r *http.Request, data interface{}, pagination *Pagination, metadata *Metadata)

SendPaginatedWithMetadata 发送带元数据的分页响应

func SendSuccess

func SendSuccess(w http.ResponseWriter, r *http.Request, data interface{})

SendSuccess 发送成功响应

Types

type APIResponse

type APIResponse[T any] struct {
	Type      ResponseType `json:"type"`
	Success   bool         `json:"success"`
	Data      T            `json:"data,omitempty"`
	Error     *ErrorInfo   `json:"error,omitempty"`
	Metadata  *Metadata    `json:"metadata,omitempty"`
	Timestamp time.Time    `json:"timestamp"`
	RequestID string       `json:"request_id"`
}

APIResponse 通用API响应结构

func ErrorResponse

func ErrorResponse(err error) *APIResponse[any]

ErrorResponse 创建错误响应的便捷函数

func PaginatedResponse

func PaginatedResponse[T any](data T, pagination *Pagination) *APIResponse[T]

PaginatedResponse 创建分页响应的便捷函数

func SuccessResponse

func SuccessResponse[T any](data T) *APIResponse[T]

SuccessResponse 创建成功响应的便捷函数

type AppError

type AppError struct {
	// 基本错误信息
	Code      ErrorCode     `json:"code"`
	Message   string        `json:"message"`
	Details   string        `json:"details,omitempty"`
	Operation string        `json:"operation"`
	Timestamp time.Time     `json:"timestamp"`
	TraceID   string        `json:"trace_id"`
	Severity  ErrorSeverity `json:"severity"`

	// 错误分类
	Category  ErrorCategory `json:"category"`
	UserError bool          `json:"user_error"` // 是否为用户输入错误

	// HTTP相关
	HTTPStatusCode int               `json:"http_status_code"`
	HTTPHeaders    map[string]string `json:"http_headers,omitempty"`

	// 重试信息
	Retryable  bool          `json:"retryable"`
	RetryDelay time.Duration `json:"retry_delay,omitempty"`
	RetryCount int           `json:"retry_count,omitempty"`

	// 上下文信息
	Context map[string]interface{} `json:"context,omitempty"`

	// 原始错误
	Cause error `json:"-"`
}

AppError 应用程序错误

func GameNotFoundError

func GameNotFoundError(operation, gameID string) *AppError

func InternalError

func InternalError(operation string, cause error) *AppError

func InvalidInputError

func InvalidInputError(operation string, field, value string, cause error) *AppError

func New

func New(code ErrorCode, operation string, cause error) *AppError

全局便捷函数

func Newf

func Newf(code ErrorCode, operation string, cause error, format string, args ...interface{}) *AppError

func NotFoundError

func NotFoundError(operation, resourceType, resourceID string) *AppError

func Wrap

func Wrap(cause error, operation string) *AppError

func (*AppError) Error

func (e *AppError) Error() string

Error 实现error接口

func (*AppError) Is

func (e *AppError) Is(target error) bool

Is 检查错误类型

func (*AppError) String

func (e *AppError) String() string

String 返回错误的字符串表示

func (*AppError) ToJSON

func (e *AppError) ToJSON() map[string]interface{}

ToJSON 返回JSON格式的错误信息

func (*AppError) Unwrap

func (e *AppError) Unwrap() error

Unwrap 返回原始错误

func (*AppError) WithContext

func (e *AppError) WithContext(key string, value interface{}) *AppError

WithContext 添加上下文信息

func (*AppError) WithDetails

func (e *AppError) WithDetails(details string) *AppError

WithDetails 添加详细信息

func (*AppError) WithHTTPHeader

func (e *AppError) WithHTTPHeader(key, value string) *AppError

WithHTTPHeader 添加HTTP头

func (*AppError) WithRetry

func (e *AppError) WithRetry(delay time.Duration, count int) *AppError

WithRetry 设置重试信息

type DefaultMetricsCollector

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

DefaultMetricsCollector 默认指标收集器

func NewDefaultMetricsCollector

func NewDefaultMetricsCollector() *DefaultMetricsCollector

NewDefaultMetricsCollector 创建默认指标收集器

func (*DefaultMetricsCollector) GetErrorCounts

func (dmc *DefaultMetricsCollector) GetErrorCounts() map[ErrorCode]int64

GetErrorCounts 获取错误计数

func (*DefaultMetricsCollector) GetErrorDurations

func (dmc *DefaultMetricsCollector) GetErrorDurations() map[ErrorCode]time.Duration

GetErrorDurations 获取错误持续时间

func (*DefaultMetricsCollector) GetRequestCounts

func (dmc *DefaultMetricsCollector) GetRequestCounts() map[string]int64

GetRequestCounts 获取请求计数

func (*DefaultMetricsCollector) IncrementErrorCount

func (dmc *DefaultMetricsCollector) IncrementErrorCount(code ErrorCode, severity ErrorSeverity, category ErrorCategory)

IncrementErrorCount 增加错误计数

func (*DefaultMetricsCollector) IncrementHTTPRequestCount

func (dmc *DefaultMetricsCollector) IncrementHTTPRequestCount(method, path, statusCode string)

IncrementHTTPRequestCount 增加HTTP请求计数

func (*DefaultMetricsCollector) RecordErrorDuration

func (dmc *DefaultMetricsCollector) RecordErrorDuration(code ErrorCode, duration time.Duration)

RecordErrorDuration 记录错误持续时间

func (*DefaultMetricsCollector) RecordHTTPRequestDuration

func (dmc *DefaultMetricsCollector) RecordHTTPRequestDuration(method, path string, duration time.Duration)

RecordHTTPRequestDuration 记录HTTP请求持续时间

func (*DefaultMetricsCollector) Reset

func (dmc *DefaultMetricsCollector) Reset()

Reset 重置所有指标

func (*DefaultMetricsCollector) ToJSON

func (dmc *DefaultMetricsCollector) ToJSON() []byte

ToJSON 将指标转换为JSON

type DefaultTraceGenerator

type DefaultTraceGenerator struct{}

DefaultTraceGenerator 默认追踪ID生成器

func (*DefaultTraceGenerator) GenerateTraceID

func (d *DefaultTraceGenerator) GenerateTraceID() string

type ErrorAnalyzer

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

ErrorAnalyzer 错误分析器

func NewErrorAnalyzer

func NewErrorAnalyzer(maxErrors int, collector MetricsCollector) *ErrorAnalyzer

NewErrorAnalyzer 创建错误分析器

func (*ErrorAnalyzer) AddError

func (ea *ErrorAnalyzer) AddError(err *AppError)

AddError 添加错误到分析器

func (*ErrorAnalyzer) Clear

func (ea *ErrorAnalyzer) Clear()

Clear 清空错误记录

func (*ErrorAnalyzer) GetStats

func (ea *ErrorAnalyzer) GetStats() *ErrorStats

GetStats 获取错误统计信息

func (*ErrorAnalyzer) GetTopErrors

func (ea *ErrorAnalyzer) GetTopErrors(limit int) []ErrorCode

GetTopErrors 获取最常见的错误

type ErrorCategory

type ErrorCategory string

ErrorCategory 错误分类

const (
	CategoryValidation ErrorCategory = "validation"
	CategoryBusiness   ErrorCategory = "business"
	CategoryDatabase   ErrorCategory = "database"
	CategoryNetwork    ErrorCategory = "network"
	CategoryAuth       ErrorCategory = "auth"
	CategoryPermission ErrorCategory = "permission"
	CategoryExternal   ErrorCategory = "external"
	CategorySystem     ErrorCategory = "system"
)

type ErrorCode

type ErrorCode string

ErrorCode 错误码类型

const (
	// 通用错误码 (1000-1999)
	ErrCodeInternal     ErrorCode = "INTERNAL_ERROR"
	ErrCodeInvalidInput ErrorCode = "INVALID_INPUT"
	ErrCodeNotFound     ErrorCode = "NOT_FOUND"
	ErrCodeUnauthorized ErrorCode = "UNAUTHORIZED"
	ErrCodeForbidden    ErrorCode = "FORBIDDEN"
	ErrCodeConflict     ErrorCode = "CONFLICT"
	ErrCodeTimeout      ErrorCode = "TIMEOUT"
	ErrCodeRateLimit    ErrorCode = "RATE_LIMIT"

	// 业务错误码 (2000-2999)
	ErrCodeGameNotFound      ErrorCode = "GAME_NOT_FOUND"
	ErrCodeGameAlreadyExist  ErrorCode = "GAME_ALREADY_EXIST"
	ErrCodeGameDisabled      ErrorCode = "GAME_DISABLED"
	ErrCodeInvalidGameStatus ErrorCode = "INVALID_GAME_STATUS"

	// 数据库错误码 (3000-3999)
	ErrCodeDatabaseError     ErrorCode = "DATABASE_ERROR"
	ErrCodeConnectionLost    ErrorCode = "CONNECTION_LOST"
	ErrCodeTransactionFailed ErrorCode = "TRANSACTION_FAILED"

	// 网络错误码 (4000-4999)
	ErrCodeNetworkError       ErrorCode = "NETWORK_ERROR"
	ErrCodeServiceUnavailable ErrorCode = "SERVICE_UNAVAILABLE"
	ErrCodeConnectionTimeout  ErrorCode = "CONNECTION_TIMEOUT"

	// 认证授权错误码 (5000-5999)
	ErrCodeTokenExpired            ErrorCode = "TOKEN_EXPIRED"
	ErrCodeInvalidToken            ErrorCode = "INVALID_TOKEN"
	ErrCodeInvalidCredentials      ErrorCode = "INVALID_CREDENTIALS"
	ErrCodeInsufficientPermissions ErrorCode = "INSUFFICIENT_PERMISSIONS"
)

预定义错误码

type ErrorCollection

type ErrorCollection struct {
	Errors []*AppError `json:"errors"`
	Total  int         `json:"total"`
}

ErrorCollection 错误集合,用于批量错误处理

func (*ErrorCollection) Add

func (ec *ErrorCollection) Add(err *AppError)

Add 添加错误到集合

func (*ErrorCollection) Error

func (ec *ErrorCollection) Error() string

Error 实现error接口

func (*ErrorCollection) First

func (ec *ErrorCollection) First() *AppError

First 返回第一个错误

func (*ErrorCollection) GetByCode

func (ec *ErrorCollection) GetByCode(code ErrorCode) []*AppError

GetByCode 根据错误码获取错误

func (*ErrorCollection) GetBySeverity

func (ec *ErrorCollection) GetBySeverity(severity ErrorSeverity) []*AppError

GetBySeverity 根据严重级别获取错误

func (*ErrorCollection) HasErrors

func (ec *ErrorCollection) HasErrors() bool

HasErrors 检查是否有错误

func (*ErrorCollection) Is

func (ec *ErrorCollection) Is(target error) bool

Is 检查是否包含特定错误

type ErrorConfig

type ErrorConfig struct {
	Code           ErrorCode
	Message        string
	HTTPStatusCode int
	Severity       ErrorSeverity
	Category       ErrorCategory
	UserError      bool
	Retryable      bool
	DefaultDetails string
}

ErrorConfig 错误配置

func GetErrorConfig

func GetErrorConfig(code ErrorCode) (ErrorConfig, error)

GetErrorConfig 获取错误配置

type ErrorFactory

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

ErrorFactory 错误工厂

func NewErrorFactory

func NewErrorFactory(serviceName string) *ErrorFactory

NewErrorFactory 创建错误工厂

func (*ErrorFactory) ConflictError

func (f *ErrorFactory) ConflictError(operation string, resource string, cause error) *AppError

ConflictError 创建冲突错误

func (*ErrorFactory) DatabaseError

func (f *ErrorFactory) DatabaseError(operation string, query string, cause error) *AppError

DatabaseError 创建数据库错误

func (*ErrorFactory) ForbiddenError

func (f *ErrorFactory) ForbiddenError(operation string, resource string, cause error) *AppError

ForbiddenError 创建禁止访问错误

func (*ErrorFactory) GameAlreadyExistError

func (f *ErrorFactory) GameAlreadyExistError(operation, gameName string) *AppError

GameAlreadyExistError 创建游戏已存在错误

func (*ErrorFactory) GameDisabledError

func (f *ErrorFactory) GameDisabledError(operation, gameID string) *AppError

GameDisabledError 创建游戏已禁用错误

func (*ErrorFactory) GameNotFoundError

func (f *ErrorFactory) GameNotFoundError(operation, gameID string) *AppError

GameNotFoundError 创建游戏未找到错误

func (*ErrorFactory) InternalError

func (f *ErrorFactory) InternalError(operation string, cause error) *AppError

InternalError 创建内部错误

func (*ErrorFactory) InternalErrorf

func (f *ErrorFactory) InternalErrorf(operation string, cause error, format string, args ...interface{}) *AppError

InternalErrorf 创建带格式化消息的内部错误

func (*ErrorFactory) InvalidInputError

func (f *ErrorFactory) InvalidInputError(operation string, field, value string, cause error) *AppError

InvalidInputError 创建输入验证错误

func (*ErrorFactory) NetworkError

func (f *ErrorFactory) NetworkError(operation string, endpoint string, cause error) *AppError

NetworkError 创建网络错误

func (*ErrorFactory) New

func (f *ErrorFactory) New(code ErrorCode, operation string, cause error) *AppError

New 创建新的应用错误

func (*ErrorFactory) NewWithDetails

func (f *ErrorFactory) NewWithDetails(code ErrorCode, operation string, details string, cause error) *AppError

NewWithDetails 创建带详细信息的应用错误

func (*ErrorFactory) Newf

func (f *ErrorFactory) Newf(code ErrorCode, operation string, cause error, format string, args ...interface{}) *AppError

Newf 创建带格式化消息的应用错误

func (*ErrorFactory) NotFoundError

func (f *ErrorFactory) NotFoundError(operation, resourceType, resourceID string) *AppError

NotFoundError 创建资源未找到错误

func (*ErrorFactory) RateLimitError

func (f *ErrorFactory) RateLimitError(operation string, limit int, window time.Duration) *AppError

RateLimitError 创建速率限制错误

func (*ErrorFactory) ServiceUnavailableError

func (f *ErrorFactory) ServiceUnavailableError(operation, service string, cause error) *AppError

ServiceUnavailableError 创建服务不可用错误

func (*ErrorFactory) TimeoutError

func (f *ErrorFactory) TimeoutError(operation string, timeout time.Duration, cause error) *AppError

TimeoutError 创建超时错误

func (*ErrorFactory) UnauthorizedError

func (f *ErrorFactory) UnauthorizedError(operation string, cause error) *AppError

UnauthorizedError 创建未授权错误

func (*ErrorFactory) WithTraceGenerator

func (f *ErrorFactory) WithTraceGenerator(generator TraceGenerator) *ErrorFactory

WithTraceGenerator 设置追踪ID生成器

func (*ErrorFactory) Wrap

func (f *ErrorFactory) Wrap(cause error, operation string) *AppError

Wrap 包装现有错误

func (*ErrorFactory) Wrapf

func (f *ErrorFactory) Wrapf(cause error, operation string, format string, args ...interface{}) *AppError

Wrapf 包装现有错误并添加格式化消息

type ErrorInfo

type ErrorInfo struct {
	Code       ErrorCode              `json:"code"`
	Message    string                 `json:"message"`
	Details    string                 `json:"details,omitempty"`
	Operation  string                 `json:"operation,omitempty"`
	TraceID    string                 `json:"trace_id,omitempty"`
	Severity   ErrorSeverity          `json:"severity,omitempty"`
	Retryable  bool                   `json:"retryable,omitempty"`
	RetryDelay *time.Duration         `json:"retry_delay,omitempty"`
	Context    map[string]interface{} `json:"context,omitempty"`
}

ErrorInfo 错误信息

type ErrorLogger

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

ErrorLogger 错误日志记录器

func NewErrorLogger

func NewErrorLogger(serviceName, version string, enableJSON bool) *ErrorLogger

NewErrorLogger 创建错误日志记录器

func (*ErrorLogger) LogError

func (el *ErrorLogger) LogError(err *AppError, context map[string]interface{})

LogError 记录错误日志

func (*ErrorLogger) LogErrorWithMetrics

func (el *ErrorLogger) LogErrorWithMetrics(err *AppError, context map[string]interface{}, metricsCollector MetricsCollector)

LogErrorWithMetrics 记录错误并更新指标

func (*ErrorLogger) LogPanic

func (el *ErrorLogger) LogPanic(recovered interface{}, context map[string]interface{})

LogPanic 记录panic错误

type ErrorMetrics

type ErrorMetrics struct {
	Code      ErrorCode     `json:"code"`
	Operation string        `json:"operation"`
	Count     int64         `json:"count"`
	FirstSeen time.Time     `json:"first_seen"`
	LastSeen  time.Time     `json:"last_seen"`
	Duration  time.Duration `json:"duration"`
	Severity  ErrorSeverity `json:"severity"`
}

ErrorMetrics 错误指标

type ErrorSeverity

type ErrorSeverity string

ErrorSeverity 错误严重级别

const (
	SeverityLow      ErrorSeverity = "low"      // 低:不影响主要功能
	SeverityMedium   ErrorSeverity = "medium"   // 中:影响部分功能
	SeverityHigh     ErrorSeverity = "high"     // 高:影响主要功能
	SeverityCritical ErrorSeverity = "critical" // 严重:系统不可用
)

func GetSeverity

func GetSeverity(code ErrorCode) ErrorSeverity

GetSeverity 获取错误严重级别

type ErrorStats

type ErrorStats struct {
	TotalErrors      int64                   `json:"total_errors"`
	ErrorsByCode     map[ErrorCode]int64     `json:"errors_by_code"`
	ErrorsBySeverity map[ErrorSeverity]int64 `json:"errors_by_severity"`
	ErrorsByCategory map[ErrorCategory]int64 `json:"errors_by_category"`
	RecentErrors     []*AppError             `json:"recent_errors,omitempty"`
	TimeRange        TimeRange               `json:"time_range"`
}

ErrorStats 错误统计信息

type LogLevel

type LogLevel string

LogLevel 日志级别

const (
	LogLevelDebug LogLevel = "debug"
	LogLevelInfo  LogLevel = "info"
	LogLevelWarn  LogLevel = "warn"
	LogLevelError LogLevel = "error"
)

type Metadata

type Metadata struct {
	RequestID   string        `json:"request_id"`
	Version     string        `json:"version"`
	Duration    time.Duration `json:"duration,omitempty"`
	Timestamp   time.Time     `json:"timestamp"`
	Pagination  *Pagination   `json:"pagination,omitempty"`
	Performance *Performance  `json:"performance,omitempty"`
}

Metadata 响应元数据

type MetricsCollector

type MetricsCollector interface {
	IncrementErrorCount(code ErrorCode, severity ErrorSeverity, category ErrorCategory)
	RecordErrorDuration(code ErrorCode, duration time.Duration)
	IncrementHTTPRequestCount(method, path, statusCode string)
	RecordHTTPRequestDuration(method, path string, duration time.Duration)
}

MetricsCollector 指标收集器接口

type Pagination

type Pagination struct {
	Page       int   `json:"page"`
	PageSize   int   `json:"page_size"`
	Total      int64 `json:"total"`
	TotalPages int   `json:"total_pages"`
	HasNext    bool  `json:"has_next"`
	HasPrev    bool  `json:"has_prev"`
}

Pagination 分页信息

type Performance

type Performance struct {
	DatabaseQueries int           `json:"database_queries,omitempty"`
	DatabaseTime    time.Duration `json:"database_time,omitempty"`
	CacheHits       int           `json:"cache_hits,omitempty"`
	CacheMisses     int           `json:"cache_misses,omitempty"`
	ExternalCalls   int           `json:"external_calls,omitempty"`
	ExternalTime    time.Duration `json:"external_time,omitempty"`
}

Performance 性能信息

type ResponseBuilder

type ResponseBuilder[T any] struct {
	// contains filtered or unexported fields
}

ResponseBuilder 响应构建器

func NewResponseBuilder

func NewResponseBuilder[T any]() *ResponseBuilder[T]

NewResponseBuilder 创建响应构建器

func (*ResponseBuilder[T]) Build

func (rb *ResponseBuilder[T]) Build() *APIResponse[T]

Build 构建最终响应

func (*ResponseBuilder[T]) Error

func (rb *ResponseBuilder[T]) Error(err error) *ResponseBuilder[T]

Error 设置错误响应

func (*ResponseBuilder[T]) Success

func (rb *ResponseBuilder[T]) Success(data T) *ResponseBuilder[T]

Success 设置成功响应数据

func (*ResponseBuilder[T]) WithMetadata

func (rb *ResponseBuilder[T]) WithMetadata(metadata *Metadata) *ResponseBuilder[T]

WithMetadata 设置元数据

func (*ResponseBuilder[T]) WithPagination

func (rb *ResponseBuilder[T]) WithPagination(pagination *Pagination) *ResponseBuilder[T]

WithPagination 设置分页信息

func (*ResponseBuilder[T]) WithPerformance

func (rb *ResponseBuilder[T]) WithPerformance(performance *Performance) *ResponseBuilder[T]

WithPerformance 设置性能信息

func (*ResponseBuilder[T]) WithRequestID

func (rb *ResponseBuilder[T]) WithRequestID(requestID string) *ResponseBuilder[T]

WithRequestID 设置请求ID

func (*ResponseBuilder[T]) WithVersion

func (rb *ResponseBuilder[T]) WithVersion(version string) *ResponseBuilder[T]

WithVersion 设置版本信息

func (*ResponseBuilder[T]) WriteJSON

func (rb *ResponseBuilder[T]) WriteJSON(w http.ResponseWriter, r *http.Request)

WriteJSON writes JSON response to an HTTP ResponseWriter.

type ResponseType

type ResponseType string

ResponseType 响应类型

const (
	ResponseTypeSuccess ResponseType = "success"
	ResponseTypeError   ResponseType = "error"
)

type TimeRange

type TimeRange struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

TimeRange 时间范围

type TraceGenerator

type TraceGenerator interface {
	GenerateTraceID() string
}

TraceGenerator 追踪ID生成器接口

Jump to

Keyboard shortcuts

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