errors

package
v1.0.0-rc9 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2025 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package errors provides standardized error handling for the MCP Bridge system.

Index

Examples

Constants

View Source
const (
	// ShortRetryTimeout for quick recovery scenarios.
	ShortRetryTimeout = 5
	// StandardRetryTimeout for normal error recovery.
	StandardRetryTimeout = 10
	// MediumRetryTimeout for rate limiting scenarios.
	MediumRetryTimeout = 30
	// LongRetryTimeout for heavy rate limiting.
	LongRetryTimeout = 60
	// ExtendedRetryTimeout for quota limits.
	ExtendedRetryTimeout = 300
	// MaxRetryTimeout for daily quota limits.
	MaxRetryTimeout = 3600
)

Retry timeout constants (in seconds).

Variables

This section is empty.

Functions

func Error

func Error(code ErrorCode, details ...interface{}) error

Error creates a new error with the given code and optional details.

Example
// Creating basic errors
err1 := Error(GTW_AUTH_MISSING)
fmt.Printf("Error: %s\n", err1.Error())

// Creating errors with details
err2 := Error(GTW_CONN_TIMEOUT, "Connection to backend failed")
fmt.Printf("Error with details: %s\n", err2.Error())

// Checking error properties
fmt.Printf("Is retryable: %v\n", IsRetryable(err2))
fmt.Printf("HTTP Status: %d\n", GetHTTPStatus(err2))
Output:

Error: [GTW_AUTH_001] Missing authentication credentials
Error with details: [GTW_CONN_002] Connection timeout: Connection to backend failed
Is retryable: true
HTTP Status: 504

func ErrorHandlerMiddleware

func ErrorHandlerMiddleware(handler *ErrorHandler) func(http.Handler) http.Handler

ErrorHandlerMiddleware creates HTTP middleware for error handling.

func GetHTTPStatus

func GetHTTPStatus(err error) int

GetHTTPStatus returns the HTTP status code for an error.

func IsErrorCode

func IsErrorCode(err error, code ErrorCode) bool

IsErrorCode checks if an error is an MCPError with the given code.

func IsRetryable

func IsRetryable(err error) bool

IsRetryable checks if an error is retryable.

Types

type CircuitBreakerPolicy

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

CircuitBreakerPolicy implements circuit breaker pattern.

func NewCircuitBreakerPolicy

func NewCircuitBreakerPolicy(config RetryConfig, logger *zap.Logger) *CircuitBreakerPolicy

NewCircuitBreakerPolicy creates a new circuit breaker policy.

func (*CircuitBreakerPolicy) NextInterval

func (p *CircuitBreakerPolicy) NextInterval(attempt int) time.Duration

NextInterval returns retry interval for circuit breaker.

func (*CircuitBreakerPolicy) RecordFailure

func (p *CircuitBreakerPolicy) RecordFailure()

RecordFailure records a failed operation.

func (*CircuitBreakerPolicy) RecordSuccess

func (p *CircuitBreakerPolicy) RecordSuccess()

RecordSuccess records a successful operation.

func (*CircuitBreakerPolicy) ShouldRetry

func (p *CircuitBreakerPolicy) ShouldRetry(err error, attempt int) bool

ShouldRetry implements circuit breaker logic.

type CircuitState

type CircuitState int

CircuitState represents circuit breaker states.

const (
	// CircuitClosed indicates the circuit breaker is closed and allowing requests.
	CircuitClosed CircuitState = iota
	// CircuitOpen indicates the circuit breaker is open and blocking requests.
	CircuitOpen
	// CircuitHalfOpen indicates the circuit breaker is testing if the service has recovered.
	CircuitHalfOpen
)

type ErrorCode

type ErrorCode string

ErrorCode represents a unique error code for the MCP Bridge system.

const (
	// Common errors (CMN_XXX_XXX) - 1000-1999.
	CMN_INT_UNKNOWN      ErrorCode = "CMN_INT_001" // Unknown internal error
	CMN_INT_PANIC        ErrorCode = "CMN_INT_002" // Panic recovery
	CMN_INT_TIMEOUT      ErrorCode = "CMN_INT_003" // Operation timeout
	CMN_INT_CONTEXT_CANC ErrorCode = "CMN_INT_004" // Context canceled
	CMN_INT_NOT_IMPL     ErrorCode = "CMN_INT_005" // Feature not implemented

	CMN_VAL_INVALID_REQ ErrorCode = "CMN_VAL_001" // Invalid request format

	CMN_VAL_MISSING_FLD ErrorCode = "CMN_VAL_002" // Required field missing

	CMN_VAL_INVALID_TYPE ErrorCode = "CMN_VAL_003" // Invalid field type

	CMN_VAL_OUT_OF_RANGE ErrorCode = "CMN_VAL_004" // Value out of acceptable range

	CMN_VAL_PATTERN_FAIL ErrorCode = "CMN_VAL_005" // Pattern validation failed

	CMN_PROTO_INVALID_VER ErrorCode = "CMN_PROTO_001" // Invalid protocol version

	CMN_PROTO_PARSE_ERR ErrorCode = "CMN_PROTO_002" // Protocol parsing error

	CMN_PROTO_MARSHAL_ERR ErrorCode = "CMN_PROTO_003" // Protocol marshaling error

	CMN_PROTO_METHOD_UNK ErrorCode = "CMN_PROTO_004" // Unknown method

	CMN_PROTO_BATCH_ERR ErrorCode = "CMN_PROTO_005" // Batch request error

	// Authentication errors.
	GTW_AUTH_MISSING      ErrorCode = "GTW_AUTH_001" // Missing authentication
	GTW_AUTH_INVALID      ErrorCode = "GTW_AUTH_002" // Invalid credentials
	GTW_AUTH_EXPIRED      ErrorCode = "GTW_AUTH_003" // Expired token
	GTW_AUTH_INSUFFICIENT ErrorCode = "GTW_AUTH_004" // Insufficient permissions
	GTW_AUTH_REVOKED      ErrorCode = "GTW_AUTH_005" // Revoked credentials
	GTW_AUTH_METHOD_UNK   ErrorCode = "GTW_AUTH_006" // Unknown auth method
	GTW_AUTH_CERT_FAIL    ErrorCode = "GTW_AUTH_007" // Certificate validation failed
	GTW_AUTH_OAUTH_FAIL   ErrorCode = "GTW_AUTH_008" // OAuth2 flow failed

	// Connection errors.
	GTW_CONN_REFUSED      ErrorCode = "GTW_CONN_001" // Connection refused
	GTW_CONN_TIMEOUT      ErrorCode = "GTW_CONN_002" // Connection timeout
	GTW_CONN_CLOSED       ErrorCode = "GTW_CONN_003" // Connection closed
	GTW_CONN_LIMIT        ErrorCode = "GTW_CONN_004" // Connection limit reached
	GTW_CONN_TLS_FAIL     ErrorCode = "GTW_CONN_005" // TLS handshake failed
	GTW_CONN_UPGRADE_FAIL ErrorCode = "GTW_CONN_006" // WebSocket upgrade failed

	// Rate limiting errors.
	GTW_RATE_LIMIT_REQ   ErrorCode = "GTW_RATE_001" // Request rate limit exceeded
	GTW_RATE_LIMIT_CONN  ErrorCode = "GTW_RATE_002" // Connection rate limit exceeded
	GTW_RATE_LIMIT_BURST ErrorCode = "GTW_RATE_003" // Burst limit exceeded
	GTW_RATE_LIMIT_QUOTA ErrorCode = "GTW_RATE_004" // Quota exceeded

	// Security errors.
	GTW_SEC_BLOCKED_IP ErrorCode = "GTW_SEC_001" // IP address blocked
	GTW_SEC_BLOCKED_UA ErrorCode = "GTW_SEC_002" // User agent blocked
	GTW_SEC_MALICIOUS  ErrorCode = "GTW_SEC_003" // Malicious request detected
	GTW_SEC_CSRF_FAIL  ErrorCode = "GTW_SEC_004" // CSRF validation failed

	// Connection errors.
	RTR_CONN_NO_BACKEND   ErrorCode = "RTR_CONN_001" // No backend available
	RTR_CONN_BACKEND_ERR  ErrorCode = "RTR_CONN_002" // Backend connection error
	RTR_CONN_POOL_FULL    ErrorCode = "RTR_CONN_003" // Connection pool exhausted
	RTR_CONN_UNHEALTHY    ErrorCode = "RTR_CONN_004" // Backend unhealthy
	RTR_CONN_CIRCUIT_OPEN ErrorCode = "RTR_CONN_005" // Circuit breaker open

	// Routing errors.
	RTR_ROUTE_NO_MATCH ErrorCode = "RTR_ROUTE_001" // No matching route
	RTR_ROUTE_CONFLICT ErrorCode = "RTR_ROUTE_002" // Route conflict
	RTR_ROUTE_DISABLED ErrorCode = "RTR_ROUTE_003" // Route disabled
	RTR_ROUTE_REDIRECT ErrorCode = "RTR_ROUTE_004" // Route requires redirect

	// Protocol errors.
	RTR_PROTO_MISMATCH   ErrorCode = "RTR_PROTO_001" // Protocol version mismatch
	RTR_PROTO_TRANSFORM  ErrorCode = "RTR_PROTO_002" // Protocol transformation error
	RTR_PROTO_SIZE_LIMIT ErrorCode = "RTR_PROTO_003" // Message size limit exceeded
)

func GetErrorCode

func GetErrorCode(err error) ErrorCode

GetErrorCode extracts the error code from an error.

type ErrorDetail

type ErrorDetail struct {
	Code        string                 `json:"code"`
	Message     string                 `json:"message"`
	Details     string                 `json:"details,omitempty"`
	Retryable   bool                   `json:"retryable"`
	Remediation string                 `json:"remediation,omitempty"`
	Context     map[string]interface{} `json:"context,omitempty"`
}

ErrorDetail contains the error details.

type ErrorDetails

type ErrorDetails struct {
	Code      string `json:"code"`
	Details   string `json:"details,omitempty"`
	Retryable bool   `json:"retryable"`
	Timestamp string `json:"timestamp"`
}

ErrorDetails contains additional error information.

type ErrorHandler

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

ErrorHandler provides centralized error handling.

func NewErrorHandler

func NewErrorHandler(logger *zap.Logger) *ErrorHandler

NewErrorHandler creates a new error handler.

func (*ErrorHandler) HandleError

func (h *ErrorHandler) HandleError(w http.ResponseWriter, r *http.Request, err error)

HandleError handles an error and writes an appropriate response.

func (*ErrorHandler) HandleJSONRPCError

func (h *ErrorHandler) HandleJSONRPCError(err error) map[string]interface{}

HandleJSONRPCError handles an error for JSON-RPC responses.

type ErrorInfo

type ErrorInfo struct {
	Code        ErrorCode   `json:"code"`
	Message     string      `json:"message"`
	Details     interface{} `json:"details,omitempty"`
	HTTPStatus  int         `json:"http_status"`
	Recoverable bool        `json:"recoverable"`
	RetryAfter  int         `json:"retry_after,omitempty"` // Seconds to wait before retry
}

ErrorInfo contains detailed information about an error.

func GetErrorInfo

func GetErrorInfo(code ErrorCode) (ErrorInfo, bool)

GetErrorInfo returns the error information for a given error code.

type ErrorResponse

type ErrorResponse struct {
	Error     ErrorDetail `json:"error"`
	RequestID string      `json:"request_id,omitempty"`
	Timestamp string      `json:"timestamp"`
}

ErrorResponse represents the standardized error response format.

type ExponentialBackoffPolicy

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

ExponentialBackoffPolicy implements exponential backoff with jitter.

func NewExponentialBackoffPolicy

func NewExponentialBackoffPolicy(config RetryConfig, logger *zap.Logger) *ExponentialBackoffPolicy

NewExponentialBackoffPolicy creates a new exponential backoff policy.

func (*ExponentialBackoffPolicy) NextInterval

func (p *ExponentialBackoffPolicy) NextInterval(attempt int) time.Duration

NextInterval calculates the next retry interval.

func (*ExponentialBackoffPolicy) ShouldRetry

func (p *ExponentialBackoffPolicy) ShouldRetry(err error, attempt int) bool

ShouldRetry determines if an error should be retried.

type GRPCErrorInterceptor

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

GRPCErrorInterceptor provides gRPC error handling.

func NewGRPCErrorInterceptor

func NewGRPCErrorInterceptor(logger *zap.Logger) *GRPCErrorInterceptor

NewGRPCErrorInterceptor creates a new gRPC error interceptor.

func (*GRPCErrorInterceptor) StreamServerInterceptor

func (i *GRPCErrorInterceptor) StreamServerInterceptor() grpc.StreamServerInterceptor

StreamServerInterceptor creates a stream server interceptor for error handling.

func (*GRPCErrorInterceptor) UnaryServerInterceptor

func (i *GRPCErrorInterceptor) UnaryServerInterceptor() grpc.UnaryServerInterceptor

UnaryServerInterceptor creates a unary server interceptor for error handling.

type MCPError

type MCPError struct {
	ErrorInfo
}

MCPError represents an MCP system error.

func (*MCPError) Error

func (e *MCPError) Error() string

Error implements the error interface.

func (*MCPError) HasCode

func (e *MCPError) HasCode(code ErrorCode) bool

HasCode checks if the error matches the given code.

func (*MCPError) WithDetails

func (e *MCPError) WithDetails(details interface{}) *MCPError

WithDetails returns a new error with additional details.

type RetryConfig

type RetryConfig struct {
	MaxAttempts     int
	InitialInterval time.Duration
	MaxInterval     time.Duration
	Multiplier      float64
	RandomizeFactor float64
}

RetryConfig defines retry behavior configuration.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns default retry configuration.

type RetryManager

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

RetryManager manages retry operations.

func NewRetryManager

func NewRetryManager(policy RetryPolicy, logger *zap.Logger) *RetryManager

NewRetryManager creates a new retry manager.

func (*RetryManager) Execute

func (m *RetryManager) Execute(ctx context.Context, operation RetryOperation) error

Execute executes an operation with retry logic.

type RetryOperation

type RetryOperation func(ctx context.Context) error

RetryOperation represents a retryable operation.

type RetryPolicy

type RetryPolicy interface {
	ShouldRetry(err error, attempt int) bool
	NextInterval(attempt int) time.Duration
}

RetryPolicy defines the retry policy interface.

Jump to

Keyboard shortcuts

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