lazy_errors

Effortlessly create, group, and nest arbitrary errors, and defer error handling ergonomically.
use ;
use ;
Running the example will print:
Got an error with 3 children.
---------------------------------------------------------
There were one or more errors
- number too large to fit in target type
at src/main.rs:9:26
- Input '❓' is invalid: invalid digit found in string
at src/main.rs:16:18
at lazy_errors/src/try_collect_or_stash.rs:148:35
at lazy_errors/src/stash_err.rs:145:46
- Input '❗' is invalid: invalid digit found in string
at src/main.rs:16:18
at lazy_errors/src/try_collect_or_stash.rs:148:35
at lazy_errors/src/stash_err.rs:145:46
In a Nutshell
lazy_errors provides types, traits, and blanket implementations
on Result that can be used to ergonomically defer error handling.
lazy_errors allows you to easily create ad-hoc errors
as well as wrap a wide variety of errors in a single common error type,
simplifying your codebase.
In that latter regard, it is similar to anyhow/eyre,
except that its reporting isn’t as fancy or detailed (for example,
lazy_errors tracks source code file name and line numbers instead of
providing full std::backtrace support).
On the other hand, lazy_errors adds methods to Result
that let you continue on failure,
deferring returning Err results.
lazy_errors allows you to return two or more errors
from functions simultaneously and ergonomically.
lazy_errors also supports nested errors.
When you return nested errors from functions,
errors will form a tree while “bubbling up”.
You can report that error tree the user/developer in its entirety.
lazy_errors integrates with core::error::Error
and is #![no_std] by default.
By default, lazy_errors will box your error values (like anyhow/eyre),
which allows you to use different error types in the same Result type.
However, lazy_errors will respect static error type information
if you provide it explicitly.
If you do so, you can access fields and methods of your error values
at run-time without needing downcasts.
Both modes of operation can work together, as will be shown
in the example on the bottom of the page.
When you define a few simple type aliases,
lazy_errors also easily supports custom error types that aren’t
Sync or even Send.
Common reasons to use the lazy_errors crate are:
- You want to return an error but run some fallible cleanup logic before.
- More generally, you’re calling two or more functions that return
Result, and want to return an error that wraps all errors that occurred. - You’re spawning several parallel activities, wait for their completion, and want to return all errors that occurred.
- You want to aggregate multiple errors before running some reporting or recovery logic, iterating over all errors collected.
- You need to handle errors that don’t implement
core::error::Error/Display/Debug/Send/Syncor other common traits.
Feature Flags
std(disabled by default):- Support any error type that implements
std::error::Error(instead ofcore::error::Error) - Implement
std::error::Errorforlazy_errorserror types (instead ofcore::error::Error) - Enable this flag if you’re on Rust v1.80 or older (
core::error::Errorwas stabilized in Rust v1.81)
- Support any error type that implements
eyre: Addsinto_eyre_resultandinto_eyre_reportconversionsrust-v$N(where$Nis a Rust version number): Add support for error types fromcoreandallocthat were stabilized in the respective Rust version.
MSRV
The MSRV of lazy_errors depends on the set of enabled features:
- Rust v1.81 and later supports all features and combinations thereof
- Rust v1.61 .. v1.81 need you to disable all
rust-v$Nfeatures where$Nis greater than the version of your Rust toolchain. For example, to compilelazy_errorson Rust v1.69, you have to disablerust-v1.81andrust-v1.77, but notrust-v1.69. eyreneeds at least Rust v1.65- Rust versions older than v1.61 are unsupported
- In Rust versions below v1.81,
core::error::Erroris not stable yet. If you’re using a Rust version before v1.81, please consider enabling thestdfeature to makelazy_errorsusestd::core::Errorinstead.
Walkthrough
lazy_errors can actually support any error type as long as it’s Sized;
it doesn’t even need to be Send or Sync. You only need to specify
the generic type parameters accordingly, as will be shown in the example
on the bottom of this page. Usually however, you’d want to use the
aliased types from the prelude. When you’re using these aliases,
errors will be boxed and you can dynamically return groups of errors
of differing types from the same function. When you’re also using
the default feature flags, lazy_errors is #![no_std] and
integrates with core::error::Error. In that case,
lazy_errors supports any error type that implements core::error::Error,
and all error types from this crate implement core::error::Error as well.
In Rust versions below v1.81, core::error::Error is not stable yet.
If you’re using an old Rust version, please disable (at least)
the rust-v1.81 feature and enable the std feature instead.
Enabling the std feature will make lazy_errors use std::error::Error
instead of core::error::Error. If you’re using an old Rust version and
need #![no_std] support nevertheless, please use the types from
the surrogate_error_trait::prelude instead of the regular prelude.
If you do so, lazy_errors will box any error type that implements the
surrogate_error_trait::Reportable marker trait.
If necessary, you can implement that trait for your custom types as well
(it’s just a single line).
While lazy_errors works standalone, it’s not intended to replace
anyhow or eyre. Instead, this project was started to explore
approaches on how to run multiple fallible operations, aggregate
their errors (if any), and defer the actual error handling/reporting
by returning all of these errors from functions that return Result.
Generally, Result<_, Vec<_>> can be used for this purpose,
which is not much different from what lazy_errors does internally.
However, lazy_errors provides “syntactic sugar”
to make this approach more ergonomic.
Thus, arguably the most useful method in this crate is or_stash.
Example: or_stash on Result
or_stash is arguably the most useful method of this crate.
It becomes available on Result as soon as you
import the OrStash trait or the prelude.
Here’s an example:
use ;
use ;
In the example above, run() will print 42, run cleanup(),
and then return the stashed errors.
Note that the ErrorStash is created manually in the example above.
The ErrorStash is empty before the first error is added.
Converting an empty ErrorStash to Result will produce Ok(()).
When or_stash is called on Result::Err(e),
e will be moved into the ErrorStash. As soon as there is
at least one error stored in the ErrorStash, converting ErrorStash
into Result will yield a Result::Err that contains an Error,
the main error type from this crate.
Example: or_create_stash on Result
Sometimes you don’t want to create an empty ErrorStash beforehand.
In that case you can call or_create_stash on Result
to create a non-empty container on-demand, whenever necessary.
When or_create_stash is called on Result::Err, the error
will be put into a StashWithErrors instead of an ErrorStash.
ErrorStash and StashWithErrors behave similarly.
While both ErrorStash and StashWithErrors can take additional
errors, a StashWithErrors is guaranteed to be non-empty.
The type system will be aware that there is at least one error.
Thus, while ErrorStash can only be converted into Result,
yielding either Ok(()) or Err(e) (where e is Error),
this distinction allows converting StashWithErrors into Error
directly.
use ;
use ;
Example: stash_err on Iterator
Quite similarly to calling or_stash on Result,
you can call stash_err on Iterator<Item = Result<T, E>>
to turn it into Iterator<Item = T>,
moving any E item into an error stash as soon as they are encountered:
use ;
use ;
let numbers = parse_input.unwrap;
assert_eq!;
Example: try_collect_or_stash on Iterator
try_collect_or_stash is a counterpart to Iterator::try_collect
from the Rust standard library that will not short-circuit,
but instead move all Err items into an error stash.
As explained above,
calling stash_err on Iterator<Item = Result<…>>
will turn a sequence of Result<T, E> into a sequence of T.
That method is most useful for
chaining another method on the resulting Iterator<Item = T>
before calling Iterator::collect.
Furthermore, when using stash_err together with collect,
there will be no indication of whether
the iterator contained any Err items:
all Err items will simply be moved into the error stash.
If you don’t need to chain any methods between calling
stash_err and collect, or if
you need collect to fail (lazily) if
the iterator contained any Err items,
you can call try_collect_or_stash
on Iterator<Item = Result<…>> instead:
use ;
use ;
let err = parse_input.unwrap_err;
let msg = format!;
assert_eq!;
Example: try_map_or_stash on arrays
try_map_or_stash is a counterpart to array::try_map
from the Rust standard library that will not short-circuit,
but instead move all Err elements/results into an error stash.
It will touch all elements of arrays
of type [T; _] or [Result<T, E>; _],
mapping each T or Ok(T) via the supplied mapping function.
Each time an Err element is encountered
or an element is mapped to an Err value,
that error will be put into the supplied error stash:
use ;
use ;
let mut errs = new;
let input1: = ;
let input2: = ;
let input3: = ;
let numbers = input1.try_map_or_stash;
let numbers = numbers.ok.unwrap;
assert_eq!;
let _ = input2.try_map_or_stash;
let _ = input3.try_map_or_stash;
let err = errs.into_result.unwrap_err;
let msg = format!;
assert_eq!;
Example: Hierarchies
As you might have noticed, Errors form hierarchies:
use ;
use ;
The example above may seem unwieldy. In fact, that example only serves
the purpose to illustrate the error hierarchy.
In practice, you wouldn’t write such code.
Instead, you’d probably rely on or_wrap or or_wrap_with.
Example: Wrapping on Result
You can use or_wrap or or_wrap_with to wrap any value
that can be converted into the
inner error type of Error
or to attach some context to an error:
use ;
use ;
Example: Ad-Hoc Errors
The err! macro allows you to format a string
and turn it into an ad-hoc Error at the same time:
use *;
use *;
let pid = 42;
let err: Error = err!;
You’ll often find ad-hoc errors to be the leaves in an error tree. However, the error tree can have almost any inner error type as leaf.
Example: into_eyre_*
ErrorStash and StashWithErrors can be converted into
Result and Error, respectively. A similar, albeit lossy,
conversion from ErrorStash and StashWithErrors exist for
eyre::Result and eyre::Error (i.e. eyre::Report), namely
into_eyre_result and
into_eyre_report:
use bail;
use *;
Supported Error Types
The prelude module
exports commonly used traits and aliased types.
Importing lazy_errors::prelude::*
should set you up for most use-cases.
You may also want to import lazy_errors::Result.
When core::error::Error is not available
(i.e. in ![no_std] mode before Rust v1.81),
you can import the surrogate_error_trait::prelude instead, and use
the corresponding lazy_errors::surrogate_error_trait::Result.
When you’re using the aliased types from the prelude, this crate should
support any Result<_, E> if E implements Into<Stashable>.
Stashable is, basically, a Box<dyn E>, where E is either
core::error::Error (Rust v1.81 or later),
std::error::Error (before Rust v1.81 if std is enabled),
or a surrogate error trait otherwise
(surrogate_error_trait::Reportable).
Thus, using the aliased types from the prelude, any error you put into
any of the containers defined by this crate will be boxed.
The Into<Box<dyn E>> trait bound was chosen because it is implemented
for a wide range of error types or “error-like” types.
Some examples of types that satisfy this constraint are:
&strStringanyhow::Erroreyre::Reportcore::error::Error- All error types from this crate
The primary error type from this crate is Error.
You can convert all supported error-like types into Error
by calling or_wrap or or_wrap_with.
In other words, this crate supports a wide variety of error types.
However, in some cases you might need a different kind of flexibility
than that. For example, maybe you don’t want to lose static error type
information or maybe your error types aren’t Sync.
In general, this crate should work well with any Result<_, E>
if E implements Into<I> where I is named the
inner error type of Error.
This crate will store errors as type I in its containers, for example
in ErrorStash or in Error. When you’re using the type aliases
from the prelude, I will always be Stashable.
However, you do not need to use Stashable at all.
You can chose the type to use for I arbitrarily.
It can be a custom type and does not need to implement any traits
or auto traits except Sized.
Thus, if the default aliases defined in the prelude
do not suit your purpose, you can import the required traits
and types manually and define custom aliases, as shown in the next example.
Example: Custom Error Types
Here’s a complex example that does not use the prelude
but instead defines its own aliases. In the example, Error<CustomError>
and ParserErrorStash don’t box their errors. Instead, they have all
error type information present statically, which allows you to write
recovery logic without having to rely on downcasts at run-time.
The example also shows how such custom error types
can still be used alongside the boxed error types (Stashable)
with custom lifetimes.
use ;
use Stashable;
use Stashable;
// Use `CustomError` as inner error type `I` for `ErrorStash`:
type ParserErrorStash<'a, F, M> = ;
// Allow using `CustomError` as `I` but use `Stashable` by default:
pub type Error<I = > = Error;
Running the example above will produce an output similar to this:
stdout:
Step #1: Starting...
Step #1: Trying to parse '42'
Step #1: Trying to parse '0xA'
Step #1: Trying to parse 'f'
Step #1: Trying to parse 'oobar'
Step #1: Trying to parse '3b'
Step #1: Done. 2 of 5 inputs were u32 (decimal or hex): [42, 10]
There were errors.
Errors will be returned after showing some suggestions.
Step #2: Starting...
Step #2: 'f' is not u32. Did you mean '0xF'?
Step #2: 'oobar' is not u32. Aborting program.
stderr:
Application failed
- Input has correctable or uncorrectable errors
- Input 'f' is not u32
at src/lib.rs:72:52
- Input 'oobar' is not u32
at src/lib.rs:72:52
- Input '3b' is not u32
at src/lib.rs:72:52
at src/lib.rs:43:14
- Unsupported input 'oobar': invalid digit found in string
at src/lib.rs:120:17
at src/lib.rs:45:18
License
Licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.