
In our example, we currently have two errors - reqwest::Error and chrono::format::ParseError. Instead of boxed errors, we can return custom errors.įor library code, we can convert all the errors to our own custom error and propagate them instead of boxed errors.If you return boxed errors, then your consumers need to be aware of the errors created by your code, your dependencies, and so on!.Errors from your library are often handled by your consumers so they need to be structured and easy to perform exhaustive match on.Errors are part of your library’s API, so your consumers know what errors to expect and recover from.In Rust, types are mostly a compile-time concept, they don’t really exist when your program is running. In dynamic languages, downcasting is trivial thanks to runtime reflection, more specifically, runtime metadata about types. A “library” can be open source crates, internal libraries etc Now we will explore the dynamic language side of Rust with the Any trait.
#Rust any downcast code
The code you’re writing would be consumed by other code.Most errors generated by application code won’t be handled but instead logged or reported to the user.The code you’re writing would be used by end users.A good rule of thumb is to question whether the code you’re writing is an “application” or a “library”: Application However, saying something is a “downside” is not very useful without context. To handle the different errors in different ways, we need to downcast them to concrete types and this casting can fail at runtime.

When we return something as Box, the concrete type information is erased. See also: downcast, downcast_mut Applications vs LibrariesĪs mentioned previously, the downside to boxed errors is that if we want to handle the underlying errors, we need to be aware of the implementation details.
If the copy method returns Box
Let date = parsed_date.format("%Y %B %d").to_string() Let parsed_date = NaiveDate::parse_from_str(formatted_date.as_str(), "%Y-%m-%d")? The Result type is an enum that has two variants - Ok(T) for successful value or Err(E) for error value: enum Result ", res, res + 1, res) In Rust, you return something called a Result. In languages like Java, JS, Python etc, you usually throw exceptions and return successful values.

Error handling in Rust is very different if you’re coming from other languages.
