WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Rust · Expert · question 74 of 100

How do you create a custom error type in Rust that can interoperate with other error types from different crates? Provide an example.?

📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

In Rust, you can create a custom error type by implementing the ‘std::error::Error‘ trait for your struct or enum. This trait requires two methods to be implemented: ‘fn description(&self) -> &str‘ and ‘fn cause(&self) -> Option<&dyn Error>‘.

To interoperate with other error types from different crates, you can implement the ‘From‘ trait for your custom error type, which allows you to convert your error type to other error types.

Here’s an example of how to create a custom error type and interoperate with other error types:

    use std::error;
    use std::fmt;
    
    #[derive(Debug)]
    enum CustomError {
        ReadError,
        WriteError,
    }
    
    impl fmt::Display for CustomError {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match self {
                CustomError::ReadError => write!(f, "Error reading file"),
                CustomError::WriteError => write!(f, "Error writing file"),
            }
        }
    }
    
    impl error::Error for CustomError {
        fn description(&self) -> &str {
            match self {
                CustomError::ReadError => "Error reading file",
                CustomError::WriteError => "Error writing file",
            }
        }
        
        fn cause(&self) -> Option<&dyn error::Error> {
            None
        }
    }
    
    impl From<std::io::Error> for CustomError {
        fn from(error: std::io::Error) -> Self {
            match error.kind() {
                std::io::ErrorKind::NotFound => CustomError::ReadError,
                _ => CustomError::WriteError,
            }
        }
    }
    
    fn main() -> Result<(), Box<dyn error::Error>> {
        let file = std::fs::File::open("unknown.txt")?;
        
        Ok(())
    }

In this example, we define a custom error type ‘CustomError‘ that has two variants: ‘ReadError‘ and ‘WriteError‘. We implement the ‘Display‘ trait to format the error message and the ‘Error‘ trait to provide the error description and cause.

We also implement the ‘From‘ trait to allow conversion from ‘std::io::Error‘ to ‘CustomError‘. This conversion is based on the error kind of the ‘std::io::Error‘.

In the ‘main()‘ function, we try to open a non-existent file, which will result in a ‘std::io::Error‘. However, we can convert this error to our ‘CustomError‘ type using the ‘?‘ operator, which will result in a boxed ‘dyn error::Error‘.

Overall, this example shows how to create a custom error type that can interoperate with other error types from different crates. This can be useful when developing libraries or applications that deal with multiple types of errors.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Rust interview — then scores it.
📞 Practice Rust — free 15 min
📕 Buy this interview preparation book: 100 Rust questions & answers — PDF + EPUB for $5

All 100 Rust questions · All topics