error_handling/
error_handling.rs

1use substrate::{hook_function, utils};
2use substrate::error::SubstrateError;
3
4fn demonstrate_error_handling() {
5    println!("=== Error Handling Example ===\n");
6
7    unsafe {
8        println!("1. Testing null pointer hook:");
9        match hook_function(std::ptr::null_mut::<u8>(), std::ptr::null_mut()) {
10            Ok(_) => println!("  Unexpected success"),
11            Err(SubstrateError::NullPointer) => println!("  ✓ Correctly caught null pointer"),
12            Err(e) => println!("  Different error: {}", e),
13        }
14
15        println!("\n2. Testing library not found:");
16        match utils::find_library("nonexistent.so") {
17            Ok(_) => println!("  Unexpected success"),
18            Err(SubstrateError::LibraryNotFound(name)) => {
19                println!("  ✓ Correctly caught missing library: {}", name)
20            }
21            Err(e) => println!("  Different error: {}", e),
22        }
23
24        println!("\n3. Testing invalid offset string:");
25        match utils::string_to_offset("not_a_hex") {
26            Ok(_) => println!("  Unexpected success"),
27            Err(SubstrateError::ParseError(msg)) => {
28                println!("  ✓ Correctly caught parse error: {}", msg)
29            }
30            Err(e) => println!("  Different error: {}", e),
31        }
32
33        println!("\n4. Testing valid hex parsing:");
34        match utils::string_to_offset("0x123ABC") {
35            Ok(offset) => println!("  ✓ Successfully parsed: 0x{:X}", offset),
36            Err(e) => println!("  ✗ Unexpected error: {}", e),
37        }
38    }
39
40    println!("\n=== All Error Cases Handled ===");
41}
42
43fn main() {
44    demonstrate_error_handling();
45
46    println!("\n=== Comprehensive Error Handling ===\n");
47    println!("Always handle errors properly in production code:");
48    println!();
49    println!("match hook_function(target, hook) {{");
50    println!("    Ok(original) => {{");
51    println!("        // Success - use original");
52    println!("    }}");
53    println!("    Err(SubstrateError::NullPointer) => {{");
54    println!("        // Handle null pointer");
55    println!("    }}");
56    println!("    Err(SubstrateError::HookFailed(msg)) => {{");
57    println!("        // Handle hook failure");
58    println!("    }}");
59    println!("    Err(e) => {{");
60    println!("        // Handle other errors");
61    println!("    }}");
62    println!("}}");
63}