61 lines
1.4 KiB
Markdown
61 lines
1.4 KiB
Markdown
|
|
---
|
||
|
|
id: 550e8400-e29b-41d4-a716-446655440000
|
||
|
|
type: note
|
||
|
|
title: Example Note - Rust Error Handling
|
||
|
|
created: 2026-01-17T10:30:00Z
|
||
|
|
modified: 2026-01-17T10:35:00Z
|
||
|
|
tags: ["rust", "error-handling", "best-practices"]
|
||
|
|
status: active
|
||
|
|
relates_to:
|
||
|
|
- guideline-rust-errors
|
||
|
|
- pattern-result-type
|
||
|
|
depends_on:
|
||
|
|
- guideline-rust-basics
|
||
|
|
project: knowledge-base
|
||
|
|
---
|
||
|
|
|
||
|
|
# Example Note - Rust Error Handling
|
||
|
|
|
||
|
|
This is an example of a note document generated from the `note.md.tera` template.
|
||
|
|
|
||
|
|
## Overview
|
||
|
|
|
||
|
|
Rust error handling uses the `Result<T, E>` type for recoverable errors and `panic!` for unrecoverable errors.
|
||
|
|
|
||
|
|
## Key Points
|
||
|
|
|
||
|
|
- Always use `Result<T>` for operations that can fail
|
||
|
|
- Use the `?` operator for error propagation
|
||
|
|
- Create custom error types with `thiserror`
|
||
|
|
- Provide context with error messages
|
||
|
|
|
||
|
|
## Best Practices
|
||
|
|
|
||
|
|
1. **Never use `unwrap()` in production code**
|
||
|
|
- Use `?` operator instead
|
||
|
|
- Or use `unwrap_or()`, `unwrap_or_else()` with defaults
|
||
|
|
|
||
|
|
2. **Define clear error types**
|
||
|
|
```rust
|
||
|
|
#[derive(Debug, thiserror::Error)]
|
||
|
|
pub enum MyError {
|
||
|
|
#[error("IO error: {0}")]
|
||
|
|
Io(#[from] std::io::Error),
|
||
|
|
|
||
|
|
#[error("Parse error: {0}")]
|
||
|
|
Parse(String),
|
||
|
|
}
|
||
|
|
```
|
||
|
|
|
||
|
|
3. **Provide helpful error messages**
|
||
|
|
```rust
|
||
|
|
let config = load_config()
|
||
|
|
.map_err(|e| format!("Failed to load config from {}: {}", path, e))?;
|
||
|
|
```
|
||
|
|
|
||
|
|
## References
|
||
|
|
|
||
|
|
- [[guideline-rust-errors]]
|
||
|
|
- [[pattern-result-type]]
|
||
|
|
- [[decision-use-thiserror]]
|