Stop Forwarding Errors, Start Designing Them
4 months ago
- #rust
- #error-handling
- #debugging
- Current error handling practices often just forward errors without preserving meaningful context.
- Rust's `std::error::Error` trait is flawed as it assumes a linear chain of errors, excluding scenarios with multiple sources.
- Backtraces in async code are often useless and expensive, failing to show the logical path of errors.
- The `Provide/Request` API introduces unpredictability and complexity without clear benefits.
- `thiserror` categorizes errors by origin rather than actionable responses, making recovery unclear.
- `anyhow` is too convenient, often leading to missed opportunities to add context.
- Errors should be designed with two audiences in mind: machines (for automated recovery) and humans (for debugging).
- For machines, errors should be flat, actionable, and kind-based, enabling clear decision-making.
- For humans, errors should capture rich context automatically and ergonomically.
- The `exn` library demonstrates a better approach by enforcing context at module boundaries using the type system.
- Combining machine-readable errors with human-readable context provides the best of both worlds.
- Errors are communication tools and should be designed thoughtfully, not just forwarded.