Skip to main content

Overview

The fallback middleware provides fallback responses when the primary handler fails, enabling graceful degradation of services. Use it when you need:
  • Graceful degradation
  • Default responses on failure
  • Service resilience

Installation

Quick Start

Configuration

Options

Examples

Basic Fallback

On Specific Errors

On Status Codes

Cached Response

API Reference

Functions

Technical Details

Implementation Architecture

The fallback middleware operates using a wrapper pattern that intercepts errors from downstream handlers:
  1. Error Interception: The middleware wraps the next handler in the chain and catches any returned errors
  2. Panic Recovery: When CatchPanic is enabled, it uses Go’s defer/recover mechanism to catch panics and convert them to errors
  3. Response Capture: For status code-based fallbacks (like NotFound), it uses a custom responseCapture type that wraps http.ResponseWriter to intercept status codes
  4. Handler Delegation: Based on the configuration, it delegates to the appropriate fallback handler

Key Components

  • Options: Configuration structure that defines when and how to trigger fallback responses
  • responseCapture: Internal type that captures HTTP response status codes before they’re written
  • panicError: Custom error type that wraps panic values, converting non-error panics into error types

Execution Flow

Error Handling Chain

The middleware provides multiple fallback strategies that can be composed:
  1. New(): Basic error handler with custom function
  2. Default(): Simple text response fallback
  3. JSON(): Structured JSON error responses
  4. Redirect(): Redirect-based error handling
  5. Chain(): Sequential fallback handlers with conditional logic
  6. NotFound(): Status code-specific handling for 404s
  7. ForStatus(): Generic status code-specific handling

Best Practices

  • Keep fallback responses lightweight
  • Log when fallback is triggered
  • Monitor fallback rate
  • Use cached data when possible

Testing

The fallback middleware includes comprehensive test coverage for various scenarios: