Casting error types (rocket)

Hi! I'm completely new to rust and I'm testing out the Rocket framework. I think this question is of a general character however.

In the code below i start a webserver with rocket that expects a rocket::error on fail. However the quetion mark at the "let settings =" line causes a failfast that returns a ClientSettingsParseError. This naturally doesn't let my code compile.

What is the idomatic way to solve this? Do i need to make an enum that encapsulates all my error types and return that? Or is there a way to parse ClientSettingsParseErrors (and others) to a rocket::Error?

#[rocket::main]
async fn main() -> Result<(), rocket::Error > {
    let settings = "esdb://admin:changeit@localhost:2113".parse()?;
    let client = Client::new(settings)?;

   ... more webcode


You'll want to make sure your function returns the most general type that all errors you may encounter can be converted into.

One option is to create a custom error enum that encapsulates all your possible errors, but because we're just using the return value to print an error message and finish with a non-zero exit code, there's a much simpler option.

Try returning Result<(), Box<dyn std::error::Error>> instead of rocket::Error. The standard library has a impl<E: std::error::Error> From<E> for Box<dyn std::error::Error> implementation, so ? should be able to convert pretty much any error type into it.

1 Like

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.