Built-in Handlers

Azu provides several built-in handlers for common middleware needs.

Handler::Base

Base class for all handlers.

class MyHandler < Azu::Handler::Base
  def call(context)
    # Before processing
    call_next(context)
    # After processing
  end
end

Methods

call

Handle the request. Must be implemented.

def call(context : HTTP::Server::Context)
  # Handle request
end

call_next

Pass to next handler in chain.

Handler::Rescuer

Catches exceptions and returns error responses.

Behavior

Exception
Status
Response

Response::NotFound

404

Not Found

Response::BadRequest

400

Bad Request

Response::Unauthorized

401

Unauthorized

Response::Forbidden

403

Forbidden

Response::ValidationError

422

Validation errors

Response::Error

varies

Error message

Other exceptions

500

Internal Server Error

Development Mode

In development, shows detailed error page with:

  • Exception message

  • Backtrace

  • Request details

Production Mode

Returns JSON error:

Handler::Logger

Logs HTTP requests.

Log Format

Configuration

Options:

  • log : Log - Logger instance

  • skip_paths : Array(String) - Paths to skip logging

Handler::Static

Serves static files.

Options:

  • public_dir : String - Directory to serve from

  • fallthrough : Bool - Pass to next handler if not found

  • directory_listing : Bool - Show directory listings

File Types

Automatically sets Content-Type based on extension:

  • .htmltext/html

  • .csstext/css

  • .jsapplication/javascript

  • .jsonapplication/json

  • .pngimage/png

  • .jpgimage/jpeg

Handler::CORS

Handles Cross-Origin Resource Sharing.

Options:

  • allowed_origins : Array(String) - Allowed origins (["*"] for all)

  • allowed_methods : Array(String) - Allowed HTTP methods

  • allowed_headers : Array(String) - Allowed request headers

  • exposed_headers : Array(String) - Headers exposed to client

  • max_age : Int32 - Preflight cache duration in seconds

  • allow_credentials : Bool - Allow cookies/auth

Response Headers

Handler Pipeline

Handlers execute in order:

Creating Custom Handlers

Handler Order Best Practices

  1. Rescuer - First, catches all errors

  2. CORS - Early, for preflight requests

  3. Logger - After CORS, logs all requests

  4. Static - Before auth, for public assets

  5. Auth - Before business logic

  6. Rate Limit - Protect endpoints

  7. Endpoints - Business logic

See Also

Last updated

Was this helpful?