Error Handling

  • The Result enum is used to indicate success or failure.

    enum Result<T, E> {
      Ok(T),
      Err(E),
    }
  • This is very useful especially in production code, I think we will use more custom error enum.

  • The ? operator simplifies error propagation.

    • If the result is Err, it propagates the error.

    • If Ok, it unwraps the value.

  • When your function can produce multiple error types, we can use Box<dyn std::error::Error> to erase the concrete error type.

  • This simplifies the return type while still maintaining flexibility.

errors1.rs

  • In this exercise we need to fix the return type in function generate_nametag_text to use Result<String, String> enum.

  • The Result enum is used to indicate success or failure.

    • Use Ok if success.

    • Use Err if not.

  • Then if given name is empty we return Err("Empty names aren't allowed".to_string()) instead of None.

  • If not empty then we should return Ok(format!("Hi! My name is {name}")).

errors2.rs

  • In this exercise we just need to propagate the error.

  • We can use the ? operator.

    • If the result is Err, it propagates the error.

    • If Ok, it unwraps the value.

  • So it will be like this:

errors3.rs

  • In this exercise we need to fix the error propagation.

  • Inside the main function as we can se it also propagate the error from calling function total_cost.

  • But the main function doesn't return anything so it got compile error.

  • To fix this we can add Result<(), ParseIntError> as return type in main function.

  • We also need to add Ok(()) at the end to mark as the main function is done without any error.

errors4.rs

  • In this exercise we need complete the function PositiveNonzeroInteger::new.

    • If the value is < 0 return CreationError::Negative.

    • If the value is == 0 return CreationError::Negative.

    • Else return Self(value as u64).

  • We can do this in multiple ways.

  • We can use classic if syntax like this:

  • Or we can use match syntax like this:

  • Or we also can combine both match and if.

  • All of them should fix the code.

errors5.rs

  • Similar like exercise errors3.rs we want to propagate the error out of the main function.

  • But in this case we have multiple kind/variant of Error.

  • To make the returned error dynamic we can use Box<dyn Error> like this:

errors6.rs

  • In this exercise we need to finish the custom error.

  • We need to add from_parse_int function like this:

  • The we need to change the parse code.

  • So instead of unwrap we want to map the error using map_error method and propagate the error like this:

Last updated