custom errors rust

In Rust, you can define custom error types using the std::error::Error trait. This trait provides a common interface for working with errors in Rust. To define a custom error type, you can create a struct that implements the Error trait.

Here's an example of how you can define a custom error type in Rust:

use std::error::Error;
use std::fmt;

#[derive(Debug)]
struct MyCustomError {
    message: String,
}

impl fmt::Display for MyCustomError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl Error for MyCustomError {}

fn main() -> Result<(), Box<dyn Error>> {
    let result = some_function()?;
    Ok(())
}

fn some_function() -> Result<(), MyCustomError> {
    Err(MyCustomError {
        message: String::from("Something went wrong."),
    })
}

In this example, we define a struct called MyCustomError that holds a message describing the error. We implement the Debug trait to enable printing the error with println!("{:?}", error). We also implement the Display trait to enable printing the error with println!("{}", error). Finally, we implement the Error trait, which allows our error to be used in functions that return a Result type.

In the main function, we call some_function, which returns a Result<(), MyCustomError>. If an error occurs, we return an Err variant with an instance of MyCustomError. If no error occurs, we return an Ok variant.

This is a basic example of how to define custom error types in Rust. You can customize the error struct to include additional information or implement other traits as needed.