rsRustPrimer
< Back to module

Error handling

Typed errors

A String as the error type is enough to get started, but the caller can do nothing with it except print it. An error enum lets the caller react differently to each case with a match, and tests can check exactly which error occurs.

rust
use std::fmt;
#[derive(Debug, PartialEq)]
enum ParseError {
WrongFieldCount { expected: usize, found: usize },
InvalidNumber { field: &'static str, value: String },
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ParseError::WrongFieldCount { expected, found } => {
write!(f, "{expected} champs attendus, {found} trouvés")
}
ParseError::InvalidNumber { field, value } => {
write!(f, "champ {field} : '{value}' n'est pas un nombre")
}
}
}
}
impl std::error::Error for ParseError {}
fn parse_strike(line: &str) -> Result<f64, ParseError> {
let fields: Vec<&str> = line.split(',').collect();
if fields.len() != 2 {
return Err(ParseError::WrongFieldCount { expected: 2, found: fields.len() });
}
fields[1].trim().parse().map_err(|_| ParseError::InvalidNumber {
field: "strike",
value: fields[1].trim().to_string(),
})
}
fn main() {
for line in ["T1,100", "T2", "T3,abc"] {
match parse_strike(line) {
Ok(strike) => println!("{line} -> {strike}"),
Err(e) => println!("{line} -> erreur : {e}"),
}
}
}

Two impl blocks to remember. fmt::Display defines the readable message printed by {}. std::error::Error officially declares the type as an error, which makes it compatible with Box<dyn Error> and the ecosystem. These are trait implementations: the next module explains the mechanism in detail.

Your turn

Add a NegativeQuantity(f64) variant to the enum, its message in Display, and have parse_quantity return it when the quantity is negative.

src/main.rs
use std::fmt;
#[derive(Debug)]
enum ParseError {
InvalidNumber(String),
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ParseError::InvalidNumber(value) => write!(f, "'{value}' n'est pas un nombre"),
}
}
}
fn parse_quantity(text: &str) -> Result<f64, ParseError> {
let quantity: f64 = text
.trim()
.parse()
.map_err(|_| ParseError::InvalidNumber(text.to_string()))?;
Ok(quantity)
}
fn main() {
for input in ["10", "-3", "x"] {
match parse_quantity(input) {
Ok(q) => println!("{q}"),
Err(e) => println!("erreur : {e}"),
}
}
}