I want to learn how to properly deal with errors in Rust. I have read the book and this example; now I would like to know how I should deal with errors in this function:
fn get_synch_point(&self) -> Result<pv::synch::MeasPeriods, reqwest::Error> {
let url = self.root.join("/term/pv/synch"); // self.root is url::Url
let url = match url {
Ok(url) => url,
// ** this err here is url::ParseError and can be converted to Error::Kind https://docs.rs/reqwest/0.8.3/src/reqwest/error.rs.html#54-57 **//
Err(err) => {
return Err(Error {
kind: ::std::convert::From::from(err),
url: url.ok(),
})
}
};
Ok(reqwest::get(url)?.json()?) //this return reqwest::Error or convert to pv::sych::MeasPeriods automaticly
}
This code is improper; it causes a compilation error:
error[E0451]: field `kind` of struct `reqwest::Error` is private
--> src/main.rs:34:42
|
34 | Err(err) => return Err(Error{kind: ::std::convert::From::from(err), url: url.ok()})
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ field `kind` is private
error[E0451]: field `url` of struct `reqwest::Error` is private
--> src/main.rs:34:81
|
34 | Err(err) => return Err(Error{kind: ::std::convert::From::from(err), url: url.ok()})
| ^^^^^^^^^^^^^ field `url` is private
What is a proper pattern to deal with that case? For me, reqwest::Error
in this case is a good solution so I would like to avoid defining my own error type:
enum MyError {
Request(reqwest::Error),
Url(url::ParseError) // this already a part of request::Error::Kind!!!
}
In that case, reusing the underlying error type is not possible because you cannot construct its hidden fields. And even when it is possible, I would advise against it, in order to make your code more flexible and future-proof.
Defining custom error types can involve writing a lot of boilerplate, but fortunately several libraries exist to alleviate this pain. failure, error-chain and quick-error were already mentioned above, but I would like to point you to a crate I wrote that involves even less boilerplate than the others : custom_error. With it, you can write:
Unfortunately, in your case you cannot create a
reqwest::Error
from other error types, if thereqwest
library does not provide a way to do so (and it likely doesn't). To solve this problem, which is very common, especially in applications which use multiple libraries, the proper solution would be one of the following:Declare your own custom enum with all errors your application works with (or one subsystem of your application; granularity highly depends on the project), and declare
From
conversions from all errors you work with to this enum type.As an extension of this approach, you can use
error-chain
(orquick-error
, on which error-chain is basically based) to generate such custom types and conversions in a semi-automatic way.Use a special, generic error type. There are basically two of them:
a.
Box<Error>
whereError
is defined in the standard library.b. Use the
Error
type defined in thefailure
crate.Then the question mark operator will be able to convert any compatible error to one of these types because of various
Into
andFrom
trait implementations.Note that the
failure
crate is intended to be the way to define errors promoted in the Rust community. Not only does it provide a common error type and trait (which fixes various issues with thestd::error::Error
trait; see for example here), it also has facilities to define your own error types (for example, withfailure_derive
), and for tracking error context, causes and generating backtrace. Additionally, it tries to be as compatible with the existing error handling approaches as possible, therefore it can be used to integrate with libraries which use other, older approaches (std::error::Error
,error-chain
,quick-error
) quite easily. So I strongly suggest you to consider using this crate first, before other options.I have already started using
failure
in my application projects, and I just can't express how much easier and nicer error handling has become. My approach is as follows:Define the
Result
type:Use
Result<Something>
everywhere where an error can be returned, using the question mark operator (?
) to convert between errors and functions likeerr_msg
orformat_err!
orbail!
to create my own error messages.I have yet to write a library using
failure
, but I imagine that for libraries it would be important to create more specific errors declared as an enum, which can be done with thefailure_derive
crate. For applications, though, thefailure::Error
type is more than enough.As already stated by Vladimir Matveev, the failure crate should be the starting point. Here is my solution:
This error enumeration is extendible for future needs.