Part 3: Error Handling and Result Types - Robust Production Code
Introduction
Why Rust's Error Handling is Different
The Problem with Exceptions
def fetch_data(url):
response = requests.get(url) # Might raise exception
return response.json() # Might raise another exception
# Easy to forget error handling
data = fetch_data("https://api.com") # Crashes if network errordata, err := fetchData(url)
if err != nil {
// Easy to ignore errors
}
// Forgot to check err? Silent bugs!The Result Type
Basic Result
The Option Type for Missing Values
Real Example: HTTP Request Errors
The ? Operator
? OperatorBefore and After
How ? Works
? WorksCustom Error Types
Simple String Errors
Enum-Based Errors
Real Error Type from My Scanner
Using the Custom Error
Error Handling Patterns
Pattern 1: Propagate with ?
?Pattern 2: Match for Different Handling
Pattern 3: Convert Error to Option
Pattern 4: Collect Results
Pattern 5: Continue on Errors
Option Combinators
Useful Option Methods
Real Example: WAF Detection
Result Combinators
Useful Result Methods
Error Context with anyhow
anyhowLogging Errors
Using log crate
log crateInitialize Logging
Testing Error Handling
Unit Tests
Real-World Example: Complete Scan Function
Key Takeaways
Common Patterns Summary
Next in Series
PreviousPart 2: Ownership, Borrowing, and Lifetimes - Rust's Memory SafetyNextPart 4: Async Programming with Tokio - Concurrent Execution
Last updated