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
- func AbortWithError(c *gin.Context, err *AppError)
- func ErrorHandler() gin.HandlerFunc
- func HandleError(c *gin.Context, err error)
- func Recovery() gin.HandlerFunc
- type AppError
- func BadRequest(message string) *AppError
- func Conflict(message string) *AppError
- func DatabaseError(err error) *AppError
- func Forbidden(message string) *AppError
- func GroupNotFound(groupName string) *AppError
- func InternalServer(message string) *AppError
- func InvalidCredentials() *AppError
- func KubernetesError(err error) *AppError
- func New(code string, message string) *AppError
- func NewWithDetails(code string, message string, details string) *AppError
- func NotFound(resource string) *AppError
- func QuotaExceeded(message string) *AppError
- func ServiceUnavailable(service string) *AppError
- func SessionNotFound(sessionID string) *AppError
- func SessionNotRunning(sessionID string) *AppError
- func TemplateNotFound(templateName string) *AppError
- func TokenExpired() *AppError
- func TokenInvalid() *AppError
- func Unauthorized(message string) *AppError
- func UserNotFound(username string) *AppError
- func ValidationFailed(message string) *AppError
- func Wrap(code string, message string, err error) *AppError
- type ErrorResponse
Constants ¶
const ( // Client errors (4xx) ErrCodeBadRequest = "BAD_REQUEST" 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" )
Error codes
Variables ¶
This section is empty.
Functions ¶
func AbortWithError ¶
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 ¶
HandleError is a helper function to handle errors in handlers
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 DatabaseError ¶
func GroupNotFound ¶
func InternalServer ¶
func InvalidCredentials ¶
func InvalidCredentials() *AppError
func KubernetesError ¶
func NewWithDetails ¶
NewWithDetails creates a new AppError with details
func QuotaExceeded ¶
func ServiceUnavailable ¶
func SessionNotFound ¶
func SessionNotRunning ¶
func TemplateNotFound ¶
func TokenExpired ¶
func TokenExpired() *AppError
func TokenInvalid ¶
func TokenInvalid() *AppError
func Unauthorized ¶
func UserNotFound ¶
func ValidationFailed ¶
func (*AppError) ToResponse ¶
func (e *AppError) ToResponse() ErrorResponse
ToResponse converts AppError to ErrorResponse