I dont know how to do this

how ? is it good idea ? is there better way to do the same ?

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Debug)]
pub enum Error {
    InternalError(Box<dyn std::error::Error>),
}

// impl From for any type of error
// to wrap it on InternalError

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl std::error::Error for Error {}

thanks.

What is the outcome you want to achieve? Does Error have more variants than just InternalError in your real code base?

As to the question hidden in your code snippet, you can't implement something like From<E: Error> for your custom error type, there's a conflicting implementation in the standard library.

I recommend having a look at thiserror and anyhow.

2 Likes

It is typically not a good idea to use Debug for Display purposes unless for quick and dirty solutions.

Your display prints Os { code: 2, kind: NotFound, message: "No such file or directory" } for "file not found" while the original error display is No such file or directory (os error 2).

I recommend using a crate like thiserror. The examples show how to get easily constructable and nicely formatted errors. With this adding error variants that give more context is much less work.

2 Likes

Wow! Thanks for the feedback. I will look into all your suggestions. Thanks!

Note also that, if you like anyhow, you might also look at its fork eyre.

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.