Error Handling
The
Resultenum 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.
References:
errors1.rs
In this exercise we need to fix the return type in function
generate_nametag_textto useResult<String, String>enum.The
Resultenum is used to indicate success or failure.Use
Okif success.Use
Errif not.
Then if given
nameis empty we returnErr("Empty names aren't allowed".to_string())instead ofNone.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
mainfunction as we can se it also propagate the error from calling functiontotal_cost.But the
mainfunction doesn't return anything so it got compile error.To fix this we can add
Result<(), ParseIntError>as return type inmainfunction.We also need to add
Ok(())at the end to mark as the main function is done without any error.Reference: https://stackoverflow.com/a/50459909/903350
errors4.rs
In this exercise we need complete the function
PositiveNonzeroInteger::new.If the value is
< 0returnCreationError::Negative.If the value is
== 0returnCreationError::Negative.Else return
Self(value as u64).
We can do this in multiple ways.
We can use classic
ifsyntax like this:Or we can use match syntax like this:
Or we also can combine both
matchandif.All of them should fix the code.
errors5.rs
Similar like exercise
errors3.rswe want to propagate the error out of themainfunction.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_intfunction like this:The we need to change the parse code.
So instead of unwrap we want to map the error using
map_errormethod and propagate the error like this:
Last updated