At a glance, it seems that most Rust libraries deal with external errors by wrapping them in a single enum. Wrapping every possible error that could arise is a tedious task.
I prefer Boxing Errors over wrapping errors using an enum, as the Error trait would allow for propagating an error from a function to the code that calls that function, as a way to trace it back to its origin.
error_chain! {
// The type defined for this error. These are the conventional
// and recommended names, but they can be arbitrarily chosen.
// It is also possible to leave this block out entirely, or
// leave it empty, and these names will be used automatically.
types {
Error, ErrorKind, Result;
}
// Without the `Result` wrapper:
//
// types {
// Error, ErrorKind;
// }
// Automatic conversions between this error chain and other
// error chains. In this case, it will e.g. generate an
// `ErrorKind` variant called `Dist` which in turn contains
// the `rustup_dist::ErrorKind`, with conversions from
// `rustup_dist::Error`.
//
// Optionally, some attributes can be added to a variant.
//
// This section can be empty.
links {
Another(other_error::Error) #[cfg(unix)];
}
// Automatic conversions between this error chain and other
// error types not defined by the `error_chain!`. These will be
// wrapped in a new error with, in this case, the
// `ErrorKind::Temp` variant. The description and cause will
// forward to the description and cause of the original error.
//
// Optionally, some attributes can be added to a variant.
//
// This section can be empty.
foreign_links {
Fmt(::std::fmt::Error);
Io(::std::io::Error) #[cfg(unix)];
}
// Define additional `ErrorKind` variants. The syntax here is
// the same as `quick_error!`, but the `from()` and `cause()`
// syntax is not supported.
errors {
InvalidToolchainName(t: String) {
description("invalid toolchain name")
display("invalid toolchain name: '{}'", t)
}
}
}
At a glance, it seems that most Rust libraries deal with external errors by wrapping them in a single
enum
. Wrapping every possible error that could arise is a tedious task.The
std::io
module contains anError
struct and anErrorKind
enum.Error::new
accepts aBox
ablestd::error::Error
.I prefer
Box
ingError
s over wrapping errors using anenum
, as theError
trait would allow for propagating an error from a function to the code that calls that function, as a way to trace it back to its origin.Note:
Box
allocates memory on the heap.Useful crates:
error-type
error-type
quick-error