Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a generic conversion from an object implementing the `Error` trait

Tags:

rust

I cannot get the following code to compile.

  • I get an error that From is already implemented.
  • If I remove the manual impl of From I get the error that From is not implemented.
  • If I do not implement Error it works fine.

I suppose that this is due to the blank impl impl<T> From<T> for T in core. How should I work around this? Not implementing Error is not really an option.

Code (playground)

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

#[derive(Debug)]
enum ErrorType {
    Other(Box<Error>)
}

impl fmt::Display for ErrorType {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.write_str("not implemented")
    }
}

impl Error for ErrorType {
    fn description(&self) -> &str {
        use self::ErrorType::*;
        match *self {
            Other(ref err) => err.description(),
        }
    }
}

impl<E: Error + 'static> From<E> for ErrorType {
    fn from(other: E) -> Self {
        ErrorType::Other(Box::new(other))
    }
}

fn ret_io_err() -> Result<(), io::Error> {
    Ok(())
}

fn ret_error_type() -> Result<(), ErrorType> {
    try!(ret_io_err());
    Ok(())
}

fn main() {}
like image 740
Ferio Avatar asked Oct 20 '22 08:10

Ferio


1 Answers

You don't.

That implementation would be a bit useless, anyway. It would mean that all other error types would just be immediately boxed. At that point, you might as well just make use of the existing conversions involving Box<Error> and use that instead.

If you want an error type that actually preserves the type of the unified errors, you'll need to implement From once for each of them. The error-type crate can help with defining unifying error types.

like image 130
DK. Avatar answered Oct 27 '22 17:10

DK.