---
name: rust-error-handling
description: "Best practices for error handling in Rust using Result, Option, and specialized libraries."
language: rust
---

# Rust Error Handling

Robust error handling patterns in Rust to ensure application stability and clear diagnostics.

## Guidelines
- **Use `Result<T, E>` for recoverable errors**: Return an error instead of panicking.
- **Use `Option<T>` for optional values**: Avoid using null-like patterns.
- **Propagate errors with `?`**: Use the question mark operator for concise error propagation.
- **Define custom error types**: Use enums for error types that require handling multiple failure cases.
- **Provide context with error messages**: Use crates like `anyhow` or `thiserror` to provide meaningful context to errors.
- **Avoid `panic!` in library code**: Errors should be returned to the caller, not terminate the process.
- **Distinguish between internal and external errors**: Use `thiserror` for library-internal errors and `anyhow` for application-level error management.

## Tools & Libraries
- **thiserror**: Best for defining custom error types in libraries.
- **anyhow**: Best for easy error handling in applications.
- **color-eyre**: For beautiful, colorful error reports in CLI tools.

## Trigger Scenarios
- When a function can fail and needs to return an error.
- When handling errors from external dependencies.
- When designing a public API that needs to expose error types.
- When debugging an application that is panicking unexpectedly.

<!-- synapsis-dsai-managed -->
