3 ms·
OK, here's some error handling I wrote about a year ago, for an RSS feed reader. This code calls lots of packages with their own error types. If anything fails
by Animats 10y ago
OK, here's some error handling I wrote about a year ago, for an RSS feed reader. This code
calls lots of packages with their own error types. If anything fails, an error bubbles up.
Those had to be packed up into a single type for Rust's error handling. What's changed that would make this more concise?
pub type FeedResult<T> = Result<T, FeedError>; // return type, result or error
// A set of errors that can occur handling RSS or Atom feeds.
pub enum FeedError {
FeedIoError(io::Error), // error at the I/O level
FeedHTTPError(hyper::Error), // error at the HTTP level
FeedXMLParseError(xml::BuilderError), // error at the XML level
FeedDateParseError(chrono::format::ParseError), // error at the date parsing level
FeedUnknownFeedTypeError, // wrong feed type
FeedFieldError(String), // required RSS field missing
FeedWasHTMLError(String) // expected XML, got HTML
}
//
// Encapsulate errors from each of the lower level error types
//
impl convert::From<hyper::Error> for FeedError {
fn from(err: hyper::Error) -> FeedError {
FeedError::FeedHTTPError(err)
}
}
impl convert::From<io::Error> for FeedError {
fn from(err: io::Error) -> FeedError {
FeedError::FeedIoError(err)
}
}
(More of those are required, one for each enum value...)
(Then we need this.)
// Convert FeedError to text string.
impl fmt::Display for FeedError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&FeedError::FeedIoError(ref xerr) => xerr.fmt(f), // I/O error
&FeedError::FeedHTTPError(ref xerr) => xerr.fmt(f), // HTTP error
&FeedError::FeedXMLParseError(ref xerr) => xerr.fmt(f), // XML parse error
&FeedError::FeedDateParseError(ref xerr) => xerr.fmt(f), // Date parse error
&FeedError::FeedUnknownFeedTypeError => write!(f, "Unknown feed type."),
&FeedError::FeedFieldError(ref s) => write!(f, "Required field \"{}\" missing from RSS/Atom feed.", s),
&FeedError::FeedWasHTMLError(ref s) => write!(f, "Expected an RSS/ATOM feed but received a web page \"{}\".", s)
//_(ref xerr) => xerr.fmt(f) // would be convenient, but not allowed in Rust.
}
}
This sort of thing is why I like Python's exception hierarchy. If you catch the higher level errors,
you get all the lower level ones, too, without losing the info about what went wrong.
- Arnavion 10y agohttps://crates.io/crates/error-chain https://crates.io/crates/error-chain or https://crates.io/crates/quick-error https://crates.io/crates/quick-error (which error-chain uses and adds to) provide macros to help with defining error types. Edit: Specifically with error-chain, you get: - Concise declaration of the enum for each wrapped error type (your first code block). - Automatic impl of From for each wrapped error type (your first code block). - A custom Result type (your first code block). - Concise way to define description() functions for each enum variant, which get used for the Display impl (your second block). For "foreign_links" it would forward to the wrapped error's fmt automatically, so you only need to do this for the others. - Bonuses like backtraces conditional on RUST_BACKTRACE=1
- Animats 10y agoHow well does that play with packages that don't use it? There seem to be several such packages.
- dbaupp 10y agoIt is a macro that just helps you define a type that implements the appropriate traits so of course it works with the rest of the world. No-one outside the crate that uses it even needs to notice, as one could just write out the definition by hand.
- Arnavion 10y agoThis is correct. Technically the backtrace functionality and ErrorChainIter implementation come from the error-chain crate (the former as a re-export of the backtrace crate) so your linker will notice.
- chubot 10y agoI think Python's exceptions work pretty well, but how do you make use of the hierarchy? It's not clear to me from this example. I find myself using Python exceptions in two pretty disjoint cases: 1) try/catch around a single line, where the exception is as specific as possible (e.g. KeyError, etc.). To do something specific in the error case, perhaps decrement a retry count. (Although this is one of those places where "exceptions should be exceptional" comes to mind; I don't like "except" for normal control flow...) 2) try/catch around main(), where the exception is as general as possible. To log the exceptions, or perhaps print a usage message. There doesn't seem to be much usage between those two extremes. I recently read "The Design and Evolution of C++" by Stroustrop, and it was not obvious to them to use the class hierarchy for exceptions. I'm not sure exactly where the idea originated from. (He also talks about resume after exceptions, which sounds insane today, but was pretty heavily debated at the time.) Go has no class hierarchy, and I believe the error handling is with an Error interface. Although I guess is does have some kind of subtyping by creating a more specific interface than Error by adding methods.