Skip to content

oliver-kriska/claude-elixir-phoenix / targets/pi/skills/elixir-idioms

elixir-idioms

Verified

OTP/BEAM patterns and Elixir idioms — GenServer, Supervisor, Task, Registry, pattern matching, with chains, pipes. Use when designing processes or debugging BEAM issues.

references/error-handling.md

View on GitHub
# Error Handling Reference

## Decision Tree

```
Is failure expected in normal operation?
├─ Yes → {:ok, _}/{:error, _} tuples
│   ├─ Chaining operations? → with
│   └─ Need both variants? → Provide foo/foo!
└─ No (unexpected/bug) → raise exception
    └─ Supervision handles recovery
```

## When to Use Each

| Use Exceptions | Use Error Tuples |
|----------------|------------------|
| Programming bugs | Expected failures |
| Truly unexpected errors | User input validation |
| Can't recover gracefully | Caller should handle |
| "Let it crash" scenarios | Control flow decisions |

## Tagged Tuple Pattern

```elixir
# Return error tuples for expected failures
def divide(a, b) when b != 0, do: {:ok, a / b}
def divide(_, 0), do: {:error, :division_by_zero}

# Bang variant raises for callers who want to crash
def divide!(a, b) do
  case divide(a, b) do
    {:ok, result} -> result
    {:error, reason} -> raise ArgumentError, "Cannot divide: #{reason}"
  end
end
```

## With for Happy Path

```elixir
# PREFER: with for multi-step operations
def create_order(params) do
  with {:ok, user} <- get_user(params.user_id),
       {:ok, product} <- get_product(params.product_id),
       {:ok, order} <- Orders.create(user, product) do
    {:ok, order}
  end
end

# AVOID: with for single operation
with {:ok, user} <- get_user(id), do: user  # Just use case!

# AVOID: Complex else clauses - normalize errors in helpers
with {:ok, a} <- normalize_step1(),
     {:ok, b} <- normalize_step2(a) do
  {:ok, b}
end
# Non-matching tuples pass through unchanged
```

## Assertive Map Access

```elixir
# DON'T: Silent nil for missing required keys
{point[:x], point[:y]}  # Returns {nil, nil} if keys missing!

# DO: Use .key for required keys (raises KeyError if missing)
{point.x, point.y}

# DO: Pattern match
def plot(%{x: x, y: y}), do: {x, y}  # Match fails if keys missing
```

## Rescue Only for External Code

```elixir
# DO: Rescue external library exceptions
def safe_parse(json) do
  {:ok, Jason.decode!(json)}
rescue
  e in Jason.DecodeError -> {:error, e.message}
end

# DON'T: Rescue for control flow or catch all
try do
  risky_operation()
rescue
  _ -> :error  # Never do this - masks programming errors
end
```

## Control Flow Decision Tree

```
Need to match against patterns?
├─ Yes → case
│   └─ Multiple dependent operations? → with
└─ No (boolean conditions)
    ├─ Single condition? → if
    └─ Multiple conditions? → cond
```

| Construct | Use When |
|-----------|----------|
| Function heads | First choice - most idiomatic |
| `case` | Pattern matching single value |
| `cond` | Multiple boolean conditions |
| `with` | Chaining operations returning tagged tuples |
| `if` | Single boolean check |
brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation).Stars: 322kUpdated Claude CodeCodexVerifiedInstall
brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).Stars: 198kUpdated Claude CodeCodexVerifiedInstall