errors

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2024 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package errors provides a comprehensive error handling system for the Hapax LLM gateway. It includes structured error types, JSON response formatting, request ID tracking, and integrated logging with Uber's zap logger.

The package is designed to be used throughout the Hapax codebase to provide consistent error handling and reporting. It offers several key features:

  • Structured JSON error responses with type information
  • Request ID tracking for error correlation
  • Integrated logging with zap
  • Custom error types for different scenarios
  • Middleware integration for panic recovery

Basic usage:

// Simple error response
errors.Error(w, "Something went wrong", http.StatusBadRequest)

// Type-specific error with context
errors.ErrorWithType(w, "Invalid input", errors.ValidationError, http.StatusBadRequest)

For more complex scenarios, you can use the error constructors in types.go:

err := errors.NewValidationError(requestID, "Invalid input", map[string]interface{}{
    "field": "username",
    "error": "required",
})

Package errors provides error handling middleware and utilities.

Package errors provides error response utilities.

Index

Constants

This section is empty.

Variables

View Source
var DefaultLogger *zap.Logger

DefaultLogger is the default zap logger instance used throughout the package. It is initialized to a production configuration but can be overridden using SetLogger.

Functions

func As

func As(err error, target interface{}) bool

As is a wrapper around errors.As for better error type assertion

func Error

func Error(w http.ResponseWriter, message string, code int)

Error is a drop-in replacement for http.Error that creates and writes a HapaxError with the InternalError type. It automatically includes the request ID from the response headers if available.

func ErrorHandler

func ErrorHandler(logger *zap.Logger) func(http.Handler) http.Handler

ErrorHandler wraps an http.Handler and provides error handling If a panic occurs during request processing, it:

  1. Logs the panic and stack trace
  2. Returns a 500 Internal Server Error to the client
  3. Includes the request ID in both the log and response

The panic recovery ensures that the server continues running even if individual requests panic. All panics are logged with their stack traces for debugging purposes.

Example usage:

router.Use(errors.ErrorHandler(logger))

func ErrorWithType

func ErrorWithType(w http.ResponseWriter, message string, errType ErrorType, code int)

ErrorWithType is like Error but allows specifying the error type. This is useful when you want to indicate specific error categories to the client while maintaining the simple interface of http.Error.

func LogError

func LogError(logger *zap.Logger, err error, requestID string)

LogError logs an error with its context It ensures that all errors are properly logged with their context, including:

  • Error type and message
  • Request ID
  • HTTP method and URL
  • Status code

Example usage:

errors.LogError(logger, err, requestID)

func SetLogger

func SetLogger(logger *zap.Logger)

SetLogger allows setting a custom zap logger instance. If nil is provided, the function will do nothing to prevent accidentally disabling logging.

func WriteError

func WriteError(w http.ResponseWriter, err *HapaxError)

WriteError formats and writes a HapaxError to an http.ResponseWriter. It sets the appropriate content type and status code, then writes the error as a JSON response.

Types

type ErrorResponse added in v0.0.5

type ErrorResponse struct {
	Type      ErrorType              `json:"type"`
	Message   string                 `json:"message"`
	RequestID string                 `json:"request_id"`
	Details   map[string]interface{} `json:"details,omitempty"`
}

ErrorResponse represents a standardized error response format that is returned to clients when an error occurs. It includes:

  • Error type for categorization
  • Human-readable message
  • Request ID for correlation
  • Optional details for additional context

type ErrorType

type ErrorType string

ErrorType represents different categories of errors that can occur in the Hapax system. Each type corresponds to a specific kind of error scenario and carries appropriate HTTP status codes and handling logic.

const (
	// AuthError represents authentication and authorization failures
	AuthError ErrorType = "authentication_error"

	// ValidationError represents input validation failures
	ValidationError ErrorType = "validation_error"

	// InternalError represents unexpected internal server errors
	InternalError ErrorType = "internal_error"

	// ConfigError represents configuration-related errors
	ConfigError ErrorType = "config_error"

	// ProviderError represents errors from LLM providers
	ProviderError ErrorType = "provider_error"

	// RateLimitError represents rate limiting errors
	RateLimitError ErrorType = "rate_limit_error"

	// AuthenticationError represents API key authentication failures
	AuthenticationError ErrorType = "api_key_error"

	// BadRequestError represents invalid request format or parameters
	BadRequestError ErrorType = "bad_request"

	// NotFoundError represents resource not found errors
	NotFoundError ErrorType = "not_found"

	// UnauthorizedError represents unauthorized access attempts
	UnauthorizedError ErrorType = "unauthorized"

	// TimeoutError represents timeout errors
	TimeoutError ErrorType = "timeout_error"
)

type HapaxError

type HapaxError struct {
	// Type categorizes the error for client handling
	Type ErrorType `json:"type"`

	// Message is a human-readable error description
	Message string `json:"message"`

	// Code is the HTTP status code (not exposed in JSON)
	Code int `json:"-"`

	// RequestID links the error to a specific request
	RequestID string `json:"request_id"`

	// Details contains additional error context
	Details map[string]interface{} `json:"details,omitempty"`
	// contains filtered or unexported fields
}

HapaxError is our custom error type that implements the error interface and provides additional context about the error. It is designed to be serialized to JSON for API responses while maintaining internal error context for logging and debugging.

func NewAuthError

func NewAuthError(requestID, message string, err error) *HapaxError

NewAuthError creates an authentication error with appropriate defaults. Use this for any authentication or authorization failures, such as:

  • Invalid API keys
  • Missing credentials
  • Insufficient permissions

Example:

err := NewAuthError("req_123", "Invalid API key", nil)

func NewError added in v0.0.5

func NewError(errType ErrorType, message string, code int, requestID string, details map[string]interface{}, err error) *HapaxError

NewError creates a new HapaxError with the given parameters. It is a general-purpose constructor that allows full control over the error's fields. For most cases, you should use one of the specialized constructors below.

Example:

err := NewError(InternalError, "database connection failed", 500, "req_123", nil, dbErr)

func NewInternalError

func NewInternalError(requestID string, err error) *HapaxError

NewInternalError creates an internal server error with appropriate defaults. Use this for unexpected errors that are not covered by other error types:

  • Panics
  • Database errors
  • Unexpected system failures

Example:

err := NewInternalError("req_123", dbErr)

func NewProviderError

func NewProviderError(requestID string, message string, err error) *HapaxError

NewProviderError creates a provider error with appropriate defaults. Use this when the underlying LLM provider encounters an error, such as:

  • Provider API errors
  • Model unavailability
  • Invalid provider configuration

Example:

err := NewProviderError("req_123", "Model unavailable", providerErr)

func NewRateLimitError

func NewRateLimitError(requestID string, retryAfter int) *HapaxError

NewRateLimitError creates a rate limit error with appropriate defaults. Use this when a client has exceeded their quota or rate limits, such as:

  • Too many requests per second
  • Monthly API quota exceeded
  • Concurrent request limit reached

Example:

err := NewRateLimitError("req_123", 30)

func NewValidationError

func NewValidationError(requestID, message string, validationDetails map[string]interface{}) *HapaxError

NewValidationError creates a validation error with appropriate defaults. Use this for any request validation failures, such as:

  • Invalid input formats
  • Missing required fields
  • Value constraint violations
  • Invalid request methods

Example:

err := NewValidationError("req_123", "Invalid prompt", map[string]interface{}{
    "field": "prompt",
    "error": "must not be empty",
})

func (*HapaxError) Error

func (e *HapaxError) Error() string

Error implements the error interface. It returns a string that combines the error type, message, and underlying error (if any).

func (*HapaxError) Is

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

Is implements error matching for errors.Is, allowing type-based error matching while ignoring other fields.

func (*HapaxError) Unwrap

func (e *HapaxError) Unwrap() error

Unwrap returns the underlying error, implementing the unwrap interface for error chains.

Jump to

Keyboard shortcuts

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