Let's improve previous example a little bit by returning a custom error type instead of a plain string. This will allow us to define specific error types and provide more structured error handling.
The logic of the function remains the same as the previous challenge, but the returned error type is what you need to change.
Define an enum ParsePercentageError with the following variants:
InvalidInput: for inputs that cannot be parsed as numbers.OutOfRange: for numbers that are not in the range 0-100.Implement the Error trait for ParsePercentageError. Use the std::error::Error trait and provide human-readable descriptions for each error.
Update the parse_percentage function to:
Ok(u8) if the input is a valid percentage (between 0 and 100).Err(ParsePercentageError::OutOfRange) if the number is out of range.Err(ParsePercentageError::InvalidInput) if the input is not a valid number.std::error::Error trait requires implementing the Display and Debug traits. You can derive Debug by #[derive(Debug)] and implement Display manually.std::fmt module to implement Display for the error enum, which is required for the Error trait.