EL

Elixir Error Handling

Idiomatic Elixir error handling with tagged tuples and pattern matching

Details

Language / Topic
elixirElixir
Category
Error Handling

Rules

balanced
- Return `{:ok, value}` / `{:error, reason}` tagged tuples from functions that can fail — pattern match on the result.
- Use `with` blocks to chain multiple operations that return `{:ok, _}` / `{:error, _}` — keeps the happy path clean.
- Use `raise`/`rescue` only for truly unexpected exceptions — tagged tuples are the idiomatic error handling mechanism.
- Use bang functions (`File.read!`) only when failure is a programmer error — for expected failures, use non-bang versions and handle the error tuple.
- Use `with` blocks for multi-step operations: `with {:ok, user} <- fetch_user(id), {:ok, profile} <- fetch_profile(user) do`.
- Return descriptive error tuples: `{:error, :not_found}`, `{:error, {:validation, errors}}` — not just `{:error, "something failed"}`.
- Use `try`/`rescue` only at system boundaries (e.g., HTTP handlers) to catch unexpected crashes — never in core business logic.
- Use `Ecto.Multi` for transactional operations that need atomic rollback on any step failure.
- Define custom error structs with `defexception` for errors that cross module boundaries.