DIY custom errors

โš“ Rust    ๐Ÿ“… 2025-07-10    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 6      

surdeus

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: DIY custom errors

I had a go reading 1, 2 and are still lost in creating own errors. I also found this example that โ€“ from my point of view โ€“ aims to handle different pre-existing errors the same way.

But Iโ€™d like to have a set of custom (new) errors that might be returned by a function. These errors relate do different details that should get readable if one wants to.

As Iโ€™m just starting and are not too acquainted to Rust in general and its trait-concept in special I tried to define an enum as the error-type-return in this try

use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
#[derive(Debug)]
enum MyError {
    ErrorA,
    ErrorB,
}
#[derive(Debug)]
struct ErrorA {
    detail_a: String,
}
impl Display for ErrorA {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} - argh!", self.detail_a)
    }
}
#[derive(Debug)]
struct ErrorB {
    detail_b: usize,
}
impl Display for ErrorB {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} - argh!", self.detail_b)
    }
}
type MyResult<T> = std::result::Result<T, MyError>;
fn test(n: i32) -> MyResult<String> {
    match n {
        0 => Ok("yay".to_string()),
        1 => Err(ErrorA{ detail_a : "nope".to_string() }),
        _ => Err(ErrorB{ detail_b : 42 }),
    }
}
fn main() {
    println!("Hello, world!");
    println!("0 {:?}", test(0));
    println!("1 {:?}", test(1));
    println!("2 {:?}", test(2));
}

It doesnโ€™t even compile :-((

Is there a way to return different error-typs via some enum or do I have to take the long way around and implement my error-structs to completely comply the Error-trait and then return them via Result<String, Box<dyn Error>> ?

4 posts - 2 participants

Read full topic

๐Ÿท๏ธ rust_feed