Create Custom Errors

This guide shows you how to create custom error types for your Azu application.

Basic Custom Error

Create an error by extending Azu::Response::Error:

class NotFoundError < Azu::Response::Error
  def initialize(resource : String, id : String | Int64)
    super("#{resource} with id #{id} not found", 404)
  end
end

# Usage
raise NotFoundError.new("User", params["id"])

Error with Context

Include additional context:

class ValidationError < Azu::Response::Error
  getter errors : Array(FieldError)

  def initialize(@errors : Array(FieldError))
    super("Validation failed", 422)
  end

  def to_json(io : IO)
    {
      error: message,
      details: errors.map { |e| {field: e.field, message: e.message} }
    }.to_json(io)
  end
end

record FieldError, field : String, message : String

Domain-Specific Errors

Create errors for your domain:

Error Hierarchy

Create a structured error hierarchy:

Error Responses

Create custom response formats:

Error Handler Integration

Handle custom errors:

Using Custom Errors in Endpoints

Error Documentation

Document your errors for API consumers:

See Also

Last updated

Was this helpful?