Skip to main content

Overview

The errorpage middleware provides custom error pages for HTTP error responses, replacing default error responses with branded pages. Use it when you need:
  • Custom 404 pages
  • Branded error pages
  • User-friendly error messages

Installation

Quick Start

Configuration

Options

Error code to handler mapping:

Examples

HTML Files

Inline HTML

JSON Errors

Custom Handler

Catch All Errors

API Reference

Functions

Technical Details

Implementation Overview

The errorpage middleware uses a response writer wrapper (statusWriter) to intercept HTTP status codes before they are sent to the client. This allows the middleware to:
  1. Capture Status Codes: Wraps the response writer to track status codes without immediately sending them
  2. Conditional Rendering: Only renders error pages for status codes >= 400 when no response body has been written
  3. Template Processing: Uses Go’s html/template package for rendering error pages with customizable templates
  4. Default Pages: Provides pre-configured error pages for common HTTP error codes (400, 401, 403, 404, 405, 500, 502, 503, 504)

Response Writer Wrapper

The statusWriter type intercepts WriteHeader() calls to delay status code propagation until after determining whether a custom error page should be shown:
This wrapper ensures that:
  • Status codes are captured but not immediately sent
  • Error pages are only shown when the response body hasn’t been written
  • The middleware can distinguish between different error scenarios

Error Handling Flow

  1. Request enters middleware
  2. Response writer is wrapped with statusWriter
  3. Next handler is called
  4. If status code >= 400 and no body written:
    • Custom error handler is invoked (if configured)
    • Custom 404 handler is invoked for 404s (if configured)
    • Appropriate error page is rendered using templates
  5. Response is sent to client

Best Practices

  • Keep error pages simple and fast
  • Include navigation back to home
  • Log errors for monitoring
  • Use different pages for client vs server errors

Testing

The errorpage middleware includes comprehensive test coverage for all major functionality: