1
+ ---
2
+ description: Proper Error Handling with Result and ? Operator
3
+ globs: "**/*.rs"
4
+ alwaysApply: true
5
+ ---
6
+
7
+ For more context read: https://doc.rust-lang.org/book/ch09-00-error-handling.html
8
+
9
+ - NEVER use `unwrap()` or `expect()` in production code without clear justification
10
+ - Use the `?` operator for error propagation in functions returning `Result`
11
+ - Handle `Result` and `Option` types explicitly with `match` or combinators
12
+ - Create custom error types for domain-specific errors in Robyn
13
+ - Use `map_err()` to transform errors when interfacing with PyO3
14
+ - Log errors at appropriate levels before returning them
15
+ - Return meaningful error messages for HTTP endpoints
16
+
17
+ WHY THIS MATTERS IN ROBYN:
18
+ Robyn is a high-performance web framework that interfaces between Python and Rust. Poor error handling can:
19
+ - Crash the entire web server with a single panic
20
+ - Lose critical error information when interfacing with Python
21
+ - Provide unhelpful error messages to API consumers
22
+ - Make debugging production issues nearly impossible
23
+ - Break the Python-Rust bridge unexpectedly
24
+
25
+ SCOPE: This applies to all Rust error handling, especially PyO3 integration, file I/O, and HTTP request processing in the Robyn codebase.
26
+
27
+ # Solution
28
+
29
+ Replace unwrap() with proper error handling:
30
+
31
+ ```rust
32
+ // Instead of:
33
+ let value = some_operation().unwrap();
34
+
35
+ // Use:
36
+ let value = some_operation()?;
37
+ // Or handle explicitly:
38
+ let value = match some_operation() {
39
+ Ok(val) => val,
40
+ Err(e) => {
41
+ log::error!("Operation failed: {}", e);
42
+ return Err(format!("Operation failed: {}", e));
43
+ }
44
+ };
45
+ ```
46
+
47
+ Use map_err for PyO3 integration:
48
+
49
+ ```rust
50
+ // Transform errors when interfacing with Python
51
+ let result = python_operation()
52
+ .map_err(|e| format!("Python operation failed: {}", e))?;
53
+ ```
54
+
55
+ Handle file operations safely:
56
+
57
+ ```rust
58
+ // Instead of:
59
+ let content = std::fs::read_to_string(path).unwrap();
60
+
61
+ // Use:
62
+ let content = std::fs::read_to_string(path)
63
+ .map_err(|e| format!("Failed to read file {}: {}", path, e))?;
64
+ ```
0 commit comments