ilmoi
ilmoi

Reputation: 2554

How can I generate an error::Error instance?

I'm implementing a function as part of trait like so:

impl TryFrom<(i16, i16, i16)> for Color {
    type Error = Box<dyn error::Error>;
    fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {

        if tuple.0 < 0 || tuple.1 < 0 || tuple.2 < 0 || tuple.0 > 255 || tuple.1 > 255 || tuple.2 >255 {
            return Err(Box::new(error::Error)); //how do I generate an instance of an error?
        }

        let c = Self { red: tuple.0 as u8, green: tuple.1 as u8, blue: tuple.2 as u8 };
        Ok(c)
    }
}

And I can't figure out how to generate an instance of an errror in the if statement. I've tried all of the below and none work. The compiler just isn't happy.

Err(Box::new(error::Error));
Err(Box::new(Error));
Err(Box::new(error::Error::new()));
Err(Box::new(error::Error::new("123")));

I've looked at docs for std::error::Error but I can't find an answer there. I'm new to Rust so pardon if this is stupid.

If there's some fundamental misunderstanding on my part, please let me know / point to resources I can read.

Upvotes: 4

Views: 3807

Answers (2)

user4815162342
user4815162342

Reputation: 155670

std::error::Error is a trait, not a type, so you cannot directly create an instance of it. You need to choose an existing type that implements the trait (or write a new one), and use that.

If you just need an error message, you can make use of From<&str> being implemented for Box<dyn Error>, and write:

return Err(Box::from("your message here"));

You can use any other error type as well, such as std::io::Error:

use std::io;
return Err(Box::new(io::Error::new(io::ErrorKind::Other, "your message here")));

Upvotes: 8

agrawal-d
agrawal-d

Reputation: 346

Here's a simple example that creates an instance of Err and returns an Error using ?:

use std::env;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args: Vec<String> = env::args().collect();
    println!("args: {:?}", args);

    if args.len() < 2 {
        println!("Usage: {0} <arg1>", args[0]);
        Err("Invalid CLI arguments")?  // <--- Return an error
    }

    Ok(())
}

Try it in the Playground

Upvotes: 2

Related Questions