rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Rust Error Handling Best Practices
use std::fs::File;
use std::io::{self, Read};
use std::num::ParseIntError;
// 1. Basic Result Type
fn divide(a: i32, b: i32) -> Result<i32, String> {
if b == 0 {
return Err("Division by zero".to_string());
}
Ok(a / b)
}
// 2. Using the ? operator for error propagation
fn read_file_contents(path: &str) -> io::Result<String> {
let mut file = File::open(path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
// 3. Custom Error Types
#[derive(Debug)]
enum AppError {
IoError(io::Error),
ParseError(ParseIntError),
NotFound,
}
impl From<io::Error> for AppError {
fn from(err: io::Error) -> Self {
AppError::IoError(err)
}
}
impl From<ParseIntError> for AppError {
fn from(err: ParseIntError) -> Self {
AppError::ParseError(err)
}
}
// 4. Using custom errors with ?
fn process_config(path: &str) -> Result<i32, AppError> {
let contents = read_file_contents(path)?;
let number: i32 = contents.trim().parse()?;
Ok(number * 2)
}
// 5. Option combinator methods
fn get_user_id(username: Option<String>) -> Option<i32> {
username
.filter(|name| !name.is_empty())
.map(|name| name.len() as i32)
}
// 6. Unwrapping with default values
fn get_port() -> u16 {
std::env::var("PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(8080)
}
// 7. Pattern matching for comprehensive handling
fn main() {
match divide(10, 2) {
Ok(result) => println!("Result: {}", result),
Err(e) => eprintln!("Error: {}", e),
}
// Using if let for cleaner Option handling
if let Some(value) = get_user_id(Some("alice".to_string())) {
println!("User ID: {}", value);
}
}