CR

Crystal Error Handling

Error handling in Crystal using exceptions, nil-safety, and union return types

Details

Language / Topic
crystalCrystal
Category
Error Handling

Rules

balanced
- Define custom exception classes inheriting from `Exception` or a domain-specific base: `class AuthError < Exception; end` — include a meaningful message in the constructor.
- Use the nilable union type (`String?` is `String | Nil`) to represent optional values — force unwrap with `.not_nil!` only when you have already validated presence.
- Use `rescue MyError => e` in `begin/rescue/ensure/end` blocks — always include an `ensure` block to release resources regardless of whether an exception was raised.
- Prefer `value.try { |v| use(v) }` over `value.not_nil!` when chaining operations on nilable values — it propagates nil safely without raising.