OMG! returning an error turns into a nightmare!

Hi,

i am trying to return an error from a function that is defined like so

fn login(client: &Client) -> Result<(), Box<dyn std::error::Error>> {
    if _condition_failed_ {
        let err = Box::new(Error::new(ErrorKind::Other, "Login failed!"));
        return Err(err)
    }
}

i came to this solution after trying various combination for an hour.

i read from google, that i should structs that define my own error, or use some crates, but i am working on private project, that i am trying to use only necessary crates, so i can also learn as much as possible on rust std.

is there an easy way to just return an error, and keep using ? because now i need to define a box in the heap that holds the error, which i also need to initialize.

i am looking for something as simple as Err("Login failed!") and move on..

Thanks

You can use both &'static str and String as an error type:

fn foo(a: u32) -> Result<(), Box<dyn std::error::Error>> {
    if a == 1 {
        Err("foo")?;
    }
    if a > 100 {
        let error_msg = format!("foo: {}", a);
        Err(error_msg)?;
    }
    Ok(())
}
3 Likes

You can simply return a Result<(), &'static str> and return Err("Login failed!"). This will also work with the ? syntax, as long as your other functions are returning &'static strings as their error types.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.