Error Set
Error Set simplifies error management by providing a streamlined method for defining errors and easily converting between them. Resultingly, error handling becomes both straightforward and efficient.
Error Set is inspired by Zig's error set, and offers similar functionality.
Instead of defining various enums/structs for errors and hand rolling relations, use an error set:
use error_set::error_set;
error_set! {
MediaError = BookParsingError || DownloadError || ParseUploadError;
BookParsingError = {
MissingBookDescription,
IoError(std::io::Error),
} || BookSectionParsingError;
BookSectionParsingError = {
MissingName,
NoContents,
};
DownloadError = {
InvalidUrl,
IoError(std::io::Error),
};
ParseUploadError = {
MaximumUploadSizeReached,
TimedOut,
AuthenticationFailed,
};
}
use error_set::error_set;
pub enum MediaError {
MissingBookDescription,
IoError(std::io::Error),
MissingName,
NoContents,
InvalidUrl,
MaximumUploadSizeReached,
TimedOut,
AuthenticationFailed,
}
#[automatically_derived]
impl ::core::fmt::Debug for MediaError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
MediaError::MissingBookDescription => {
::core::fmt::Formatter::write_str(f, "MissingBookDescription")
}
MediaError::IoError(__self_0) => {
::core::fmt::Formatter::debug_tuple_field1_finish(
f,
"IoError",
&__self_0,
)
}
MediaError::MissingName => {
::core::fmt::Formatter::write_str(f, "MissingName")
}
MediaError::NoContents => ::core::fmt::Formatter::write_str(f, "NoContents"),
MediaError::InvalidUrl => ::core::fmt::Formatter::write_str(f, "InvalidUrl"),
MediaError::MaximumUploadSizeReached => {
::core::fmt::Formatter::write_str(f, "MaximumUploadSizeReached")
}
MediaError::TimedOut => ::core::fmt::Formatter::write_str(f, "TimedOut"),
MediaError::AuthenticationFailed => {
::core::fmt::Formatter::write_str(f, "AuthenticationFailed")
}
}
}
}
#[allow(unused_qualifications)]
impl core::error::Error for MediaError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match *self {
MediaError::IoError(ref source) => source.source(),
#[allow(unreachable_patterns)]
_ => None,
}
}
}
impl core::fmt::Display for MediaError {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
MediaError::MissingBookDescription => {
f.write_fmt(format_args!("{0}", "MediaError::MissingBookDescription"))
}
MediaError::IoError(ref source) => f.write_fmt(format_args!("{0}", source)),
MediaError::MissingName => {
f.write_fmt(format_args!("{0}", "MediaError::MissingName"))
}
MediaError::NoContents => {
f.write_fmt(format_args!("{0}", "MediaError::NoContents"))
}
MediaError::InvalidUrl => {
f.write_fmt(format_args!("{0}", "MediaError::InvalidUrl"))
}
MediaError::MaximumUploadSizeReached => {
f.write_fmt(format_args!("{0}", "MediaError::MaximumUploadSizeReached"))
}
MediaError::TimedOut => {
f.write_fmt(format_args!("{0}", "MediaError::TimedOut"))
}
MediaError::AuthenticationFailed => {
f.write_fmt(format_args!("{0}", "MediaError::AuthenticationFailed"))
}
}
}
}
impl From<BookParsingError> for MediaError {
fn from(error: BookParsingError) -> Self {
match error {
BookParsingError::MissingBookDescription => {
MediaError::MissingBookDescription
}
BookParsingError::IoError(source) => MediaError::IoError(source),
BookParsingError::MissingName => MediaError::MissingName,
BookParsingError::NoContents => MediaError::NoContents,
}
}
}
impl From<BookSectionParsingError> for MediaError {
fn from(error: BookSectionParsingError) -> Self {
match error {
BookSectionParsingError::MissingName => MediaError::MissingName,
BookSectionParsingError::NoContents => MediaError::NoContents,
}
}
}
impl From<DownloadError> for MediaError {
fn from(error: DownloadError) -> Self {
match error {
DownloadError::InvalidUrl => MediaError::InvalidUrl,
DownloadError::IoError(source) => MediaError::IoError(source),
}
}
}
impl From<ParseUploadError> for MediaError {
fn from(error: ParseUploadError) -> Self {
match error {
ParseUploadError::MaximumUploadSizeReached => {
MediaError::MaximumUploadSizeReached
}
ParseUploadError::TimedOut => MediaError::TimedOut,
ParseUploadError::AuthenticationFailed => MediaError::AuthenticationFailed,
}
}
}
impl From<std::io::Error> for MediaError {
fn from(error: std::io::Error) -> Self {
MediaError::IoError(error)
}
}
pub enum BookParsingError {
MissingBookDescription,
IoError(std::io::Error),
MissingName,
NoContents,
}
#[automatically_derived]
impl ::core::fmt::Debug for BookParsingError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
BookParsingError::MissingBookDescription => {
::core::fmt::Formatter::write_str(f, "MissingBookDescription")
}
BookParsingError::IoError(__self_0) => {
::core::fmt::Formatter::debug_tuple_field1_finish(
f,
"IoError",
&__self_0,
)
}
BookParsingError::MissingName => {
::core::fmt::Formatter::write_str(f, "MissingName")
}
BookParsingError::NoContents => {
::core::fmt::Formatter::write_str(f, "NoContents")
}
}
}
}
#[allow(unused_qualifications)]
impl core::error::Error for BookParsingError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match *self {
BookParsingError::IoError(ref source) => source.source(),
#[allow(unreachable_patterns)]
_ => None,
}
}
}
impl core::fmt::Display for BookParsingError {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
BookParsingError::MissingBookDescription => {
f.write_fmt(
format_args!("{0}", "BookParsingError::MissingBookDescription"),
)
}
BookParsingError::IoError(ref source) => {
f.write_fmt(format_args!("{0}", source))
}
BookParsingError::MissingName => {
f.write_fmt(format_args!("{0}", "BookParsingError::MissingName"))
}
BookParsingError::NoContents => {
f.write_fmt(format_args!("{0}", "BookParsingError::NoContents"))
}
}
}
}
impl From<BookSectionParsingError> for BookParsingError {
fn from(error: BookSectionParsingError) -> Self {
match error {
BookSectionParsingError::MissingName => BookParsingError::MissingName,
BookSectionParsingError::NoContents => BookParsingError::NoContents,
}
}
}
impl From<std::io::Error> for BookParsingError {
fn from(error: std::io::Error) -> Self {
BookParsingError::IoError(error)
}
}
pub enum BookSectionParsingError {
MissingName,
NoContents,
}
#[automatically_derived]
impl ::core::fmt::Debug for BookSectionParsingError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(
f,
match self {
BookSectionParsingError::MissingName => "MissingName",
BookSectionParsingError::NoContents => "NoContents",
},
)
}
}
#[allow(unused_qualifications)]
impl core::error::Error for BookSectionParsingError {}
impl core::fmt::Display for BookSectionParsingError {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
BookSectionParsingError::MissingName => {
f.write_fmt(format_args!("{0}", "BookSectionParsingError::MissingName"))
}
BookSectionParsingError::NoContents => {
f.write_fmt(format_args!("{0}", "BookSectionParsingError::NoContents"))
}
}
}
}
pub enum DownloadError {
InvalidUrl,
IoError(std::io::Error),
}
#[automatically_derived]
impl ::core::fmt::Debug for DownloadError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
DownloadError::InvalidUrl => {
::core::fmt::Formatter::write_str(f, "InvalidUrl")
}
DownloadError::IoError(__self_0) => {
::core::fmt::Formatter::debug_tuple_field1_finish(
f,
"IoError",
&__self_0,
)
}
}
}
}
#[allow(unused_qualifications)]
impl core::error::Error for DownloadError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match *self {
DownloadError::IoError(ref source) => source.source(),
#[allow(unreachable_patterns)]
_ => None,
}
}
}
impl core::fmt::Display for DownloadError {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
DownloadError::InvalidUrl => {
f.write_fmt(format_args!("{0}", "DownloadError::InvalidUrl"))
}
DownloadError::IoError(ref source) => {
f.write_fmt(format_args!("{0}", source))
}
}
}
}
impl From<std::io::Error> for DownloadError {
fn from(error: std::io::Error) -> Self {
DownloadError::IoError(error)
}
}
pub enum ParseUploadError {
MaximumUploadSizeReached,
TimedOut,
AuthenticationFailed,
}
#[automatically_derived]
impl ::core::fmt::Debug for ParseUploadError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(
f,
match self {
ParseUploadError::MaximumUploadSizeReached => "MaximumUploadSizeReached",
ParseUploadError::TimedOut => "TimedOut",
ParseUploadError::AuthenticationFailed => "AuthenticationFailed",
},
)
}
}
#[allow(unused_qualifications)]
impl core::error::Error for ParseUploadError {}
impl core::fmt::Display for ParseUploadError {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match *self {
ParseUploadError::MaximumUploadSizeReached => {
f.write_fmt(
format_args!("{0}", "ParseUploadError::MaximumUploadSizeReached"),
)
}
ParseUploadError::TimedOut => {
f.write_fmt(format_args!("{0}", "ParseUploadError::TimedOut"))
}
ParseUploadError::AuthenticationFailed => {
f.write_fmt(
format_args!("{0}", "ParseUploadError::AuthenticationFailed"),
)
}
}
}
}
which is also equivalent to writing the full expansion:
error_set! {
MediaError = {
IoError(std::io::Error),
MissingBookDescription,
MissingName,
NoContents,
InvalidUrl,
MaximumUploadSizeReached,
TimedOut,
AuthenticationFailed,
};
BookParsingError = {
MissingBookDescription,
IoError(std::io::Error),
MissingName,
NoContents,
};
BookSectionParsingError = {
MissingName,
NoContents,
};
DownloadError = {
InvalidUrl,
IoError(std::io::Error),
};
ParseUploadError = {
MaximumUploadSizeReached,
TimedOut,
AuthenticationFailed,
};
}
Any above subset can be converted into a superset with .into() or ?.
This makes correctly scoping and passing around errors a breeze.
Error enums and error variants can also accept doc comments and attributes like #[derive(...)].
use error_set::error_set;
error_set! {
MediaError = {
IoError(std::io::Error)
} || BookParsingError || DownloadError || ParseUploadError;
BookParsingError = {
MissingBookDescription,
CouldNotReadBook(std::io::Error),
} || BookSectionParsingError;
BookSectionParsingError = {
MissingName,
NoContents,
};
DownloadError = {
InvalidUrl,
CouldNotSaveBook(std::io::Error),
};
ParseUploadError = {
MaximumUploadSizeReached,
TimedOut,
AuthenticationFailed,
};
}
fn main() {
let book_section_parsing_error: BookSectionParsingError = BookSectionParsingError::MissingName;
let book_parsing_error: BookParsingError = book_section_parsing_error.into();
assert!(matches!(book_parsing_error, BookParsingError::MissingName));
let media_error: MediaError = book_parsing_error.into();
assert!(matches!(media_error, MediaError::MissingName));
let io_error = std::io::Error::new(std::io::ErrorKind::OutOfMemory, "oops out of memory");
let result_download_error: Result<(), DownloadError> = Err(io_error).coerce(); let result_media_error: Result<(), MediaError> = result_download_error.coerce(); assert!(matches!(result_media_error, Err(MediaError::IoError(_))));
}
The typical project approach is to have one errors.rs file with a single error_set. This keeps
all the errors in one place and allows your IDE to autocomplete crate::errors:: with of all errors.
But error_set! can also be used for quick errors "unions", no longer requiring users to
hand write From<..> or use .map_err(..) for these simple cases.
e.g.
error_set! {
JwtVerifierCreationError = {
Reqwest(reqwest::Error),
Jwt(jsonwebtoken::errors::Error),
};
}
impl JwtVerifier {
pub async fn new(project_id: String) -> Result<Self, JwtVerifierCreationError> {
let public_keys = Self::fetch_public_keys().await?; let decoding_keys = public_keys
.into_iter()
.map(|(key, value)| {
DecodingKey::from_rsa_pem(value.as_bytes()).map(|decoding_key| (key, decoding_key))
})
.collect()?; ...
}
}
Error sets also supports inline structs for passing error related data and custom display messages.
Just add the #[display(...)] attribute to the variant.
error_set! {
AuthError = {
#[display("User `{}` with role `{}` does not exist", name, role)]
UserDoesNotExist {
name: String,
role: u32,
},
#[display("The provided credentials are invalid")]
InvalidCredentials
};
LoginError = {
#[display("Io Error: {0}")]
IoError(std::io::Error),
} || AuthError;
}
Note: If a custom display is not provided for a wrapped error type like IoError(std::io::Error), it will delegate its display
to the inner type (std::io::Error). If it is desired to prevent this, provide a custom display message, like in the above example, or add #[display(opaque)].
fn main() {
let x: AuthError = AuthError::UserDoesNotExist {
name: "john".to_string(),
role: 30,
};
assert_eq!(x.to_string(), "User `john` with role `30` does not exist".to_string());
let y: LoginError = x.into();
assert_eq!(y.to_string(), "User `john` with role `30` does not exist".to_string());
let x = AuthError::InvalidCredentials;
assert_eq!(x.to_string(), "The provided credentials are invalid".to_string());
}
You can even redeclare the same inline struct in a different set, change the display message, and conversion between sets will still work.
Feature Flags
coerce_macro: Each error set will generates a coerce! macro to help handle coercion between partially intersecting sets.
let val = coerce!{ setx,
Ok(val) => val,
Err(SetX::X) => {}, { Err(SetX) => return Err(SetY) } }?;
Given:
error_set! {
SetX = {
X
} || Common;
SetY = {
Y
} || Common;
Common = {
A,
B,
C,
D,
E,
F,
G,
H,
};
}
rather than writing:
fn setx_result_to_sety_result() -> Result<(), SetY> {
let _ok = match setx_result() {
Ok(ok) => ok,
Err(SetX::X) => {} Err(SetX::A) => {
return Err(SetY::A);
}
Err(SetX::B) => {
return Err(SetY::B);
}
Err(SetX::C) => {
return Err(SetY::C);
}
Err(SetX::D) => {
return Err(SetY::D);
}
Err(SetX::E) => {
return Err(SetY::E);
}
Err(SetX::F) => {
return Err(SetY::F);
}
Err(SetX::G) => {
return Err(SetY::G);
}
Err(SetX::H) => {
return Err(SetY::H);
}
};
Ok(())
}
one can write this, which compiles to the match statement above:
fn setx_result_to_sety_result() -> Result<(), SetY> {
let _ok = coerce!{ setx_result(),
Ok(ok) => ok,
Err(SetX::X) => {}, { Err(SetX) => return Err(SetY) } };
Ok(())
}
The coerce! macro is a flat fast (no tt muncher 🦫) declarative macro created by the error_set! macro for the set.
coerce! behaves like a regular match statement, except it allows a terminal coercion statement between sets. e.g.
{ Err(SetX) => return Err(SetY) }
{ Err(SetX) => Err(SetY) }
{ SetX => return SetY }
{ SetX => SetY }
With coerce!, one can concisely handle specific variants of errors as they bubble up the call stack and propagate the rest.
tracing / log / defmt :
Enables support for the tracing or log or defmt crates. Methods are added to Result and are executed when the Result is an Err for logging purposes. They work similarly to anyhow's .context(..) method. e.g.
let result: Result<(), &str> = Err("operation failed");
let value: Result<(), &str> = result.error("If `Err`, this message is logged as error via tracing/log/defmt");
let value: Result<(), &str> = result.warn("If `Err`, this message is logged as warn via tracing/log/defmt");
let value: Result<(), &str> = result.with_debug(|err| format!("If `Err`, this message is logged as debug via tracing/log/defmt: {}", err));
let value: Option<()> = result.consume_info(); let value: Option<()> = result.consume_with_trace(|err| format!("If `Err`, this message is logged as trace via tracing/log/defmt: {}", err));
Note: a context_stub feature flag also exists to be used by libraries. This allows the api's to be used in libraries
while a downstream binrary can ultimately decide the implementation. If no implementations is selected, since all the above
methods are inlined, the code will be optimized away during compilation.
Why Choose error_set Over thiserror or anyhow
error_set is a unique approach with some of the same features of thiserror and anyhow, while solving a few more problems
common to Rust developers.
Like thiserror, error_set allows you define errors, their display messages, and conversions between errors. However error_set
is more maintainable and approximately 50% more concise:
#[derive(Error)]
enum Error1 {
a,
b,
}
#[derive(Error)]
enum Error2 {
c,
d,
}
#[derive(Error)]
enum Error3 {
Error1(#[from] Error1),
Error2(#[from] Error2),
}
error_set! {
Error1 = {
a,
b
};
Error2 = {
c,
d
};
Error3 = Error1 || Error2;
}
With error_set there is no need to maintain a web of nested wrapped enums (with #[from]), since there is no nesting, and all the From implementations are automatically generated if one error type is a subset of another.
Like anyhow, error_set attempts to capture the context around errors. To accomplish this, it uses the help of tracing/log crate. See the
feature flags section for more info. However, if your project doesn't require handling specific error types and you just need to propagate errors up the call stack, then anyhow is likely a good choice for you. It's straightforward and skips the need to define error types all together.
For libraries and general projects that require precise error handling and differentiation, error management can often become complex and unwieldy
as projects grow. This may even result in "mega enums". error_set can help here where others can't.
What is a Mega Enum?
A mega enum, or mega error enum, is an enumeration that consolidates various error types into one large enum, whereas the code would be more precise if split into multiple enums.
These often arise due to refactors or developers opting for less intrusive programming approach.
This method can lead to inefficiencies and confusion because it includes error variants that are not relevant in certain scopes.
Example Scenario:
Consider the following functions and their respective error types:
func1 can produce errors a and b, represented by enum1.
func2 can produce errors c and d, represented by enum2.
func3 calls both func1 and func2.
If func3 does not handle the errors from func1 and func2, it must return an error enum that encompasses variants a, b, c, and d. Without a tool like error_set, developers might skip defining enum1 and enum2 due to the complexity and instead create a mega enum with all possible error variants (a, b, c, d). This means that any caller of func1 or func2 would have to handle all these cases, even those that are not possible in that specific context. error_set being so concise and simple, developers actually want to scope their errors to the correct context and join them when needed with a simple || operation. No need to ever think about a web of nested wrapped error types.
How error_set Simplifies Error Management:
error_set allows you to define errors quickly and precisely. Correctly scoping errors is easy and no wrapping of
various error enum types is necessary. Conversions/Propagation up the stack are as simple as .into() or ? (or coerce! macro).
error_set also makes display messages and tracking context easy.
By using error_set, your project can maintain clear and precise error definitions, enhancing code readability and maintainability without the tedious process of manually defining and managing error relations.
no_std
This crate supports #![no_std].
Cavets:
tracing/log features are not supported, but defmt is supported.