Skip to content

Elixir Error Handling — try, rescue, with, and Tagged Tuples

DodaTech Updated 2026-06-29 1 min read

In this tutorial, you will learn about Elixir Error Handling. We cover key concepts, practical examples, and best practices to help you master this topic.

Elixir's error handling follows the "let it crash" philosophy from Erlang. For expected failures, use tagged tuples. For unexpected exceptions, let supervisors handle recovery.

Try/Rescue/After

try do
  File.read!("config.json") |> Jason.decode!()
rescue
  File.Error -> {:error, "file problem"}
  e in Jason.DecodeError -> {:error, "parse error: #{e.message}"}
after
  IO.puts("Attempted to load config")
end

The With Construct

def process_user(id) do
  with {:ok, user} <- find_user(id),
       {:ok, validated} <- validate(user),
       {:ok, _} <- save(validated) do
    {:ok, :success}
  else
    {:error, :not_found} -> {:error, "User not found"}
    {:error, :invalid} -> {:error, "Validation failed"}
    _ -> {:error, "Unknown error"}
  end
end

Tagged Tuples Pattern

# {:ok, result} | {:error, reason} is the standard pattern
case File.read("config.json") do
  {:ok, content} -> Jason.decode!(content)
  {:error, reason} -> {:error, "Config load failed: #{reason}"}
end

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro