|
| 1 | +//! Lab (answer) |
| 2 | +//! Error Handling |
| 3 | +//! |
| 4 | +
|
| 5 | +#![allow(unused_assignments)] |
| 6 | +#![allow(unused_variables)] |
| 7 | +#![allow(dead_code)] |
| 8 | + |
1 | 9 | fn main() { |
2 | | - println!("TBD"); |
| 10 | + // TASK 1 - Error Result |
| 11 | + // Hint: You can return an error using a 'Result' enum variant 'Err' |
| 12 | + enum Reason { TooYoung, TooOld, } |
| 13 | + fn check_age(age: i32) -> Result<i32, Reason> { |
| 14 | + if age < 18 { |
| 15 | + Err(Reason::TooYoung) |
| 16 | + } else { |
| 17 | + Ok(age) |
| 18 | + } |
| 19 | + } |
| 20 | + let my_age = 17; |
| 21 | + |
| 22 | + // TASK 2 - Handling Results |
| 23 | + // Hint: Replace the 'unwrap()' function by a pattern matching to 'handle check_age' return |
| 24 | + match check_age(my_age) { |
| 25 | + Ok(age) => println!("Access granted! You are {} years old.", age), |
| 26 | + Err(Reason::TooYoung) => println!("Sorry, you're not old enough yet."), |
| 27 | + Err(Reason::TooOld) => println!("System error: User exceeds maximum age limit."), |
| 28 | + } |
| 29 | + |
| 30 | + // TASK 3 - The Try Operator |
| 31 | + // Hint: Use the try operator to return an error automatically to the caller of 'register' |
| 32 | + // if check_age returns an error |
| 33 | + // The try operator tries to convert 'reason' to the return type of 'register' 'string' |
| 34 | + // From trait should be implemented |
| 35 | + impl From<Reason> for String { |
| 36 | + fn from(reason: Reason) -> Self { |
| 37 | + match reason { |
| 38 | + Reason::TooYoung => "User is under the required age limit".to_string(), |
| 39 | + Reason::TooOld => "User is above the maximum age limit".to_string(), |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + fn register() -> Result<(), String> { |
| 44 | + check_age(10)?; |
| 45 | + Ok(()) |
| 46 | + } |
| 47 | + |
| 48 | + // TASK 4 - Handling Propagation |
| 49 | + // Hint: Error has been propagated from 'check_age' to 'register' to 'main' |
| 50 | + // Use pattern matching to handle return from 'register' instead of 'unwrap()' |
| 51 | + // Print a message for each possible result |
| 52 | + match register() { |
| 53 | + Ok(_) => println!("Registration successful!"), |
| 54 | + Err(e) => println!("Registration failed: {}", e), |
| 55 | + } |
| 56 | + |
| 57 | + // TASK 5 - thiserror |
| 58 | + // Hint: Convert the comments over the two variants into error text using 'thiserror' |
| 59 | + // Then make sure withdraw returns an 'AccountError' of 'InsufficientFunds' |
| 60 | + // Display the 'balance' and the 'amount' |
| 61 | + use thiserror::Error; |
| 62 | + #[derive(Error, Debug)] |
| 63 | + pub enum AccountError { |
| 64 | + #[error("insufficient funds: available {available}, requested {requested}")] |
| 65 | + InsufficientFunds { available: u64, requested: u64 }, |
| 66 | + #[error("account is inactive")] |
| 67 | + InactiveAccount, |
| 68 | + } |
| 69 | + fn withdraw(balance: u64, amount: u64) -> Result<u64, AccountError> { |
| 70 | + if amount > balance { |
| 71 | + return Err(AccountError::InsufficientFunds { |
| 72 | + available: balance, |
| 73 | + requested: amount |
| 74 | + }); |
| 75 | + } |
| 76 | + Ok(balance - amount) |
| 77 | + } |
| 78 | + |
| 79 | + // Task 6 - Anyhow |
| 80 | + // Hint: Turn the 'println' in 'process_transaction' into an additional context of information |
| 81 | + // Attached to the withdraw function |
| 82 | + // You have to use the correct library to be able to use the 'with_context' method |
| 83 | + use anyhow::Context; |
| 84 | + fn process_transaction(balance: u64, amount: u64) -> anyhow::Result<()> { |
| 85 | + withdraw(balance, amount) |
| 86 | + .with_context(|| format!("Failed to process withdrawal of ${}", amount))?; |
| 87 | + Ok(()) |
| 88 | + } |
| 89 | + let result = process_transaction(50, 100); |
| 90 | + if let Err(e) = result { |
| 91 | + // This will print a message that looks like an actual run-time error |
| 92 | + println!("Error: {}", e); |
| 93 | + // This next line will print the following : |
| 94 | + // Debug Trace: Failed to process withdrawal of $100 |
| 95 | + // Caused by: |
| 96 | + // insufficient funds: available 50, requested 100 |
| 97 | + println!("\nDebug Trace: {:?}", e); |
| 98 | + } |
3 | 99 | } |
0 commit comments