Tsallaka zuwa abun ciki
Justice Tech School

Custom Errors

Implement Display and Error for your own error type.

Example
use std::fmt;
#[derive(Debug)]
struct NegErr(i32);
impl fmt::Display for NegErr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "negative: {}", self.0) }
}
impl std::error::Error for NegErr {}
fn check(n: i32) -> Result<i32, NegErr> { if n < 0 { Err(NegErr(n)) } else { Ok(n) } }

fn main() {
    match check(-1) {
        Ok(v) => println!("{}", v),
        Err(e) => println!("error: {}", e),
    }
}

Result

error: negative: -1

Exercise

Error trait.

impl std::error:: for E {}

Quiz Test

What does Display give?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.