Using Enum Or Struct to Create Custom Error

The Rust docs showcase implementing custom error types with a struct like so:

#[derive(Debug, Clone)]
struct Error;


impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "invalid first item to double")
    }
}

However, for me, it is more natural to use enums to write errors like so


#[derive(Debug, Clone)]
enum Error {
    Error1,
    Error2
}


impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
       match *self {
           Error::Error1 => write!(f, "Error 1"),
           Error::Error2 => write!(f, "Error 2"),
       }
    }
}

What method would you suggest is more idiomatic or the preferred method of creating custom errors?

As with everything, it depends™. Returning an enum is usually more convenient, but it may hinder the expresiveness of the API where you want to limit the possible errors (i.e. functionA can only fail with Error1).

There's no silver bullet here, just give it a thought and go with whatever fits your use case the best.

Here some food for thought: Modular Errors in Rust - Sabrina Jewson.

2 Likes

Does your error type need to represent (a) just one possible failure case or (b) multiple failure cases? If (a), use a struct; if (b), use an enum.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.