errors

package
v0.0.0-...-e5d423c Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package errors provides standardized error handling for StreamSpace API.

This package implements a consistent error format across all API endpoints:

  • Structured error responses with error codes
  • Automatic HTTP status code mapping
  • Optional error details for debugging
  • Machine-readable error codes for client error handling

Error Structure:

  • Code: Machine-readable error identifier (e.g., "QUOTA_EXCEEDED")
  • Message: Human-readable error message
  • Details: Optional additional context (wrapped errors, stack traces)
  • StatusCode: HTTP status code (400, 401, 403, 404, 500, etc.)

Error Categories:

  • Client Errors (4xx): Bad request, unauthorized, forbidden, not found
  • Server Errors (5xx): Internal errors, database errors, service unavailable

Usage patterns:

// Simple error
return errors.NotFound("session")

// Error with custom message
return errors.QuotaExceeded("Maximum 5 sessions allowed")

// Wrap underlying error
return errors.DatabaseError(err)

// In HTTP handler
c.JSON(err.StatusCode, err.ToResponse())

JSON Response Format:

{
  "error": "QUOTA_EXCEEDED",
  "message": "Session quota exceeded",
  "code": "QUOTA_EXCEEDED",
  "details": "5/5 sessions active"
}

Package errors provides standardized error handling for StreamSpace API.

This file implements error handling middleware for Gin framework.

Purpose: - Centralize error handling across all API endpoints - Convert AppError to consistent JSON responses - Log errors with appropriate severity levels - Recover from panics gracefully - Provide helper functions for error responses

Features: - Automatic error logging (ERROR for 5xx, WARN for 4xx) - Panic recovery with error response - Consistent error response format - Error severity classification - Request abort on critical errors

Middleware Functions:

  • ErrorHandler: Handles AppError and generic errors
  • Recovery: Recovers from panics
  • HandleError: Helper for error responses in handlers
  • AbortWithError: Helper to abort request with error

Implementation Details: - Integrates with Gin's error handling mechanism (c.Errors) - Logs errors using standard library log (consider upgrading to structured logging) - Preserves error details for debugging - Automatically sets HTTP status codes

Thread Safety: - Middleware is thread-safe - Safe for concurrent requests

Dependencies: - github.com/gin-gonic/gin for HTTP framework

Example Usage:

// Apply error handling middleware
router.Use(errors.Recovery())
router.Use(errors.ErrorHandler())

// In handler: return error and let middleware handle it
func handler(c *gin.Context) {
    session, err := getSession(id)
    if err != nil {
        errors.HandleError(c, errors.SessionNotFound(id))
        return
    }
    c.JSON(200, session)
}

// Or abort immediately
if !authorized {
    errors.AbortWithError(c, errors.Forbidden("Access denied"))
    return
}

Index

Constants

View Source
const (
	// Client errors (4xx)
	ErrCodeBadRequest         = "BAD_REQUEST"
	ErrCodeUnauthorized       = "UNAUTHORIZED"
	ErrCodeForbidden          = "FORBIDDEN"
	ErrCodeNotFound           = "NOT_FOUND"
	ErrCodeConflict           = "CONFLICT"
	ErrCodeValidationFailed   = "VALIDATION_FAILED"
	ErrCodeQuotaExceeded      = "QUOTA_EXCEEDED"
	ErrCodeRateLimitExceeded  = "RATE_LIMIT_EXCEEDED"
	ErrCodeSessionNotRunning  = "SESSION_NOT_RUNNING"
	ErrCodeSessionNotFound    = "SESSION_NOT_FOUND"
	ErrCodeTemplateNotFound   = "TEMPLATE_NOT_FOUND"
	ErrCodeUserNotFound       = "USER_NOT_FOUND"
	ErrCodeGroupNotFound      = "GROUP_NOT_FOUND"
	ErrCodeInvalidCredentials = "INVALID_CREDENTIALS"
	ErrCodeTokenExpired       = "TOKEN_EXPIRED"
	ErrCodeTokenInvalid       = "TOKEN_INVALID"

	// Server errors (5xx)
	ErrCodeInternalServer     = "INTERNAL_SERVER_ERROR"
	ErrCodeDatabaseError      = "DATABASE_ERROR"
	ErrCodeKubernetesError    = "KUBERNETES_ERROR"
	ErrCodeServiceUnavailable = "SERVICE_UNAVAILABLE"
)

Error codes

Variables

This section is empty.

Functions

func AbortWithError

func AbortWithError(c *gin.Context, err *AppError)

AbortWithError is a helper to abort request with error

func ErrorHandler

func ErrorHandler() gin.HandlerFunc

ErrorHandler is a middleware that handles errors consistently

func HandleError

func HandleError(c *gin.Context, err error)

HandleError is a helper function to handle errors in handlers

func Recovery

func Recovery() gin.HandlerFunc

Recovery is a middleware that recovers from panics

Types

type AppError

type AppError struct {
	// Code is a machine-readable error identifier.
	// Format: UPPER_SNAKE_CASE (e.g., "QUOTA_EXCEEDED", "NOT_FOUND")
	// Used by clients for programmatic error handling.
	Code string `json:"code"`

	// Message is a human-readable error description.
	// Should be suitable for display to end users.
	// Example: "Session quota exceeded: 5/5 sessions active"
	Message string `json:"message"`

	// Details provides additional context for debugging (optional).
	// May contain wrapped error messages, stack traces, or technical details.
	// Should not be shown to end users in production.
	// Example: "database query failed: connection timeout"
	Details string `json:"details,omitempty"`

	// StatusCode is the HTTP status code to return.
	// Automatically set based on error code.
	// Not included in JSON response (marked with `json:"-"`)
	StatusCode int `json:"-"`
}

AppError represents a standardized application error with HTTP context.

AppError provides:

  • Machine-readable error code for client error handling
  • Human-readable message for display to users
  • Optional details for debugging (not always shown to clients)
  • Automatic HTTP status code mapping

Example:

err := &AppError{
    Code: "QUOTA_EXCEEDED",
    Message: "Session quota exceeded: 5/5 sessions active",
    Details: "user1 has 5 running sessions, max allowed is 5",
    StatusCode: 403,
}

func BadRequest

func BadRequest(message string) *AppError

func Conflict

func Conflict(message string) *AppError

func DatabaseError

func DatabaseError(err error) *AppError

func Forbidden

func Forbidden(message string) *AppError

func GroupNotFound

func GroupNotFound(groupName string) *AppError

func InternalServer

func InternalServer(message string) *AppError

func InvalidCredentials

func InvalidCredentials() *AppError

func KubernetesError

func KubernetesError(err error) *AppError

func New

func New(code string, message string) *AppError

New creates a new AppError

func NewWithDetails

func NewWithDetails(code string, message string, details string) *AppError

NewWithDetails creates a new AppError with details

func NotFound

func NotFound(resource string) *AppError

func QuotaExceeded

func QuotaExceeded(message string) *AppError

func ServiceUnavailable

func ServiceUnavailable(service string) *AppError

func SessionNotFound

func SessionNotFound(sessionID string) *AppError

func SessionNotRunning

func SessionNotRunning(sessionID string) *AppError

func TemplateNotFound

func TemplateNotFound(templateName string) *AppError

func TokenExpired

func TokenExpired() *AppError

func TokenInvalid

func TokenInvalid() *AppError

func Unauthorized

func Unauthorized(message string) *AppError

func UserNotFound

func UserNotFound(username string) *AppError

func ValidationFailed

func ValidationFailed(message string) *AppError

func Wrap

func Wrap(code string, message string, err error) *AppError

Wrap wraps an existing error with an AppError

func (*AppError) Error

func (e *AppError) Error() string

Error implements the error interface

func (*AppError) ToResponse

func (e *AppError) ToResponse() ErrorResponse

ToResponse converts AppError to ErrorResponse

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message"`
	Code    string `json:"code,omitempty"`
	Details string `json:"details,omitempty"`
}

ErrorResponse represents the JSON error response

Jump to

Keyboard shortcuts

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