Henry
Henry

Reputation: 587

How can I convert <dyn Error> from an Error?

I do not know the convert path from my custom error to Box, can you show me the code?

This is the code (I do not want to use err.into(), because I hope to know how rust think about it)

Thank you!

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

#[derive(Debug)]
pub enum CustomError {
    A
}

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

impl Error for CustomError {

}

fn return_error() -> Result<(),CustomError>{
    return Err(CustomError::A);
}

fn test() -> Result<(),Box<dyn Error>> {
    // it shows: expected trait object `dyn std::error::Error`, found enum `CustomError`
    return_error().map_err(|err|Box::new(err))
}


fn main() {
    test();
    println!("Hello, world!");
}

Thank you!

Upvotes: 3

Views: 1792

Answers (2)

Teo Jia Jiun
Teo Jia Jiun

Reputation: 1

There is a blanket From<E> for Box<dyn Error> implementation that you can take advantage of: -

fn test() -> Result<(), Box<dyn Error>> {
    return_error().map_err(Box::from)
}

Upvotes: 0

Netwave
Netwave

Reputation: 42716

You just need to annotate the type. By default when boxing the type would be Box<T> not Box<dyn Trait>:

fn test() -> Result<(),Box<dyn Error>> {
    // it shows: expected trait object `dyn std::error::Error`, found enum `CustomError`
    return_error().map_err(|err| {
        let dyn_err: Box<dyn Error> = Box::new(err);
        dyn_err
    })
}

Playground

Or as per @sebpuetz suggests:

.map_err(|err|Box::new(err) as Box<dyn Error>)

Upvotes: 1

Related Questions