Rust Fundamentals · 15 XP Pro

Custom error types

String errors are easy but vague. An enum lets each failure be its own variant, which callers can match on and which can carry data.

#[derive(Debug, PartialEq)]
pub enum LoginError {
    EmptyName,
    TooShort(usize),
    BadNumber(std::num::ParseIntError),
}

impl From<std::num::ParseIntError> for LoginError {
    fn from(e: std::num::ParseIntError) -> Self {
        LoginError::BadNumber(e)
    }
}

With a From impl in place, ? converts the error automatically: a function returning Result<_, LoginError> can use ? on a Result<_, ParseIntError>.

Your task

The starter already declares the enum. Everything must be pub, because the tests use your crate as lesson.

  1. Write impl From<std::num::ParseIntError> for AgeError returning AgeError::NotANumber.
  2. Write pub fn parse_age(input: &str) -> Result<u32, AgeError>:
    • trim the input; if nothing is left, return Err(AgeError::Empty)
    • parse as u32 using ? (so "abc" and "-3" give NotANumber)
    • if the age is above 150, return Err(AgeError::TooOld(age))
    • otherwise return Ok(age)

Next lesson →

Sign in to run your code. It's free.