Master Rust's error handling with Result, Option, ? operator, panic! macro, and custom error types. Learn recoverable vs unrecoverable errors.
Generate comprehensive documentation and examples for Rust error handling patterns based on "The Rust Programming Language" official book.
When the user asks for help with Rust error handling, follow these steps:
1. **Identify the Error Handling Context**
- Determine if the user needs help with recoverable errors (Result<T, E>), unrecoverable errors (panic!), or both
- Check if they're working with existing code or starting fresh
- Identify the specific error handling pattern they need (? operator, match, unwrap, expect, custom errors)
2. **Analyze Existing Code (if applicable)**
- Read the user's Rust files to understand their current error handling approach
- Look for common anti-patterns: excessive unwrap(), missing error propagation, unclear error messages
- Identify opportunities to improve error handling robustness
3. **Provide Targeted Guidance**
**For Result<T, E> (Recoverable Errors):**
- Explain when to use Result vs Option
- Demonstrate the ? operator for error propagation
- Show match expressions for explicit error handling
- Provide examples of unwrap(), expect(), unwrap_or(), unwrap_or_else()
- Illustrate map(), and_then(), or_else() for Result chaining
**For panic! (Unrecoverable Errors):**
- Explain when panic! is appropriate (bugs, invariant violations, array out-of-bounds)
- Show how to use panic! macro with custom messages
- Demonstrate unwrap() and expect() that panic on error
- Explain panic vs Result trade-offs
**For Custom Error Types:**
- Show how to define custom error enums
- Demonstrate implementing std::error::Error trait
- Explain From trait for error conversion
- Show thiserror or anyhow crate patterns (if applicable)
**For the ? Operator:**
- Explain ? operator syntax and behavior
- Show how it propagates errors up the call stack
- Demonstrate use in functions returning Result or Option
- Explain early return semantics
4. **Generate Code Examples**
- Provide working Rust code snippets demonstrating the pattern
- Include realistic scenarios (file I/O, parsing, network operations)
- Show both simple and advanced error handling techniques
- Add inline comments explaining key concepts
5. **Best Practices & Recommendations**
- Emphasize type safety and compile-time error checking
- Recommend prefer Result over panic! for library code
- Suggest descriptive error messages for expect()
- Advise on error context and debugging information
- Explain when to use error handling crates (thiserror, anyhow, eyre)
6. **Testing Error Handling**
- Show how to write tests that verify error cases
- Demonstrate should_panic attribute for panic tests
- Provide examples of testing Result error variants
**User:** "How do I handle file reading errors in Rust?"
**Response:**
```rust
use std::fs::File;
use std::io::{self, Read};
// Using Result with ? operator for error propagation
fn read_file_contents(path: &str) -> Result<String, io::Error> {
let mut file = File::open(path)?; // ? propagates error if File::open fails
let mut contents = String::new();
file.read_to_string(&mut contents)?; // ? propagates error if read fails
Ok(contents)
}
// Using match for explicit error handling
fn read_file_explicit(path: &str) -> Result<String, io::Error> {
let mut file = match File::open(path) {
Ok(f) => f,
Err(e) => return Err(e), // Explicit error return
};
let mut contents = String::new();
match file.read_to_string(&mut contents) {
Ok(_) => Ok(contents),
Err(e) => Err(e),
}
}
// Using unwrap_or_else for fallback behavior
fn read_file_with_default(path: &str) -> String {
std::fs::read_to_string(path)
.unwrap_or_else(|_| "default content".to_string())
}
```
1. **Recoverable vs Unrecoverable Errors**: Rust's dual approach to error handling
2. **Result<T, E>**: The type for recoverable errors with Ok and Err variants
3. **Option<T>**: For values that may be absent (Some/None)
4. **panic! macro**: For unrecoverable errors that should crash the program
5. **? operator**: Syntactic sugar for error propagation
6. **unwrap() and expect()**: Convenience methods that panic on error
7. **Custom Error Types**: Defining domain-specific error enums
8. **Error Trait**: Implementing std::error::Error for custom types
9. **Error Conversion**: Using From trait for automatic error type conversion
10. **Error Context**: Providing meaningful error messages and debugging info
Based on "Error Handling" chapter from The Rust Programming Language official book:
https://doc.rust-lang.org/book/ch09-00-error-handling.html
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/rust-error-handling-guide/raw