Skip to main content

neuer_error/
lib.rs

1//! The error that can be whatever you want (it is Mr. Neuer). In every case (hopefully). NO AI
2//! SLOP!
3//!
4//! An error handling library designed to be:
5//!
6//! - Useful in both libraries and applications, containing human and machine information.
7//! - Ergonomic, low-boilerplate and comfortable, while still adhering best-practices and providing
8//!   all necessary infos.
9//! - Flexible in interfacing with other error handling libraries.
10//!
11//! ## Features/Highlights
12//!
13//! - Most importantly: error messages, that are helpful for debugging. By default it uses source
14//!   locations instead of backtraces, which is often easier to follow, more efficient and works
15//!   without debug info.
16//! - Discoverable, typed context getters without generic soup, type conversions and conflicts.
17//! - Optional macro rule to force yourself at compile-time to add additional context in functions.
18//! - Compatible with non-Send/Sync environments, but also with Send/Sync environments ([per feature
19//!   flag](#feature-flags)).
20//! - Works with std and no-std, but requires a global allocator.
21//! - Out of the box source error chaining.
22//! - No dependencies by default. Optional features may lead to some dependencies.
23//! - No `unsafe` used (yet?).
24//!
25//! ## Why a new (German: neuer) error library?
26//!
27//! Long story, you can [view it here](https://github.com/FlixCoder/neuer-error/blob/main/why-another-lib.md).
28//!
29//! TLDR: I wasn't satisfied with my previous approach and existing libraries I know. And I was
30//! inspired by a blog post to experiment myself with error handling design.
31//!
32//! ## Usage
33//!
34//! The best way to see how to use it for your use-case is to check out the [examples](https://github.com/FlixCoder/neuer-error/tree/main/examples).
35//! Nevertheless, here is a quick demo:
36//!
37//! ```rust
38//! # use neuer_error::{traits::*, NeuErr, Result, provided_attachments, require_context};
39//! // In library/module:
40//! #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
41//! pub enum Retryable { No, Yes }
42//!
43//! // Provide discoverable, typed information for library users.
44//! provided_attachments!(
45//! 	retryable(single: Retryable) -> bool {
46//! 		|retryable| matches!(retryable, Some(Retryable::Yes))
47//! 	};
48//! );
49//!
50//! fn do_something_internal() -> Result<()> {
51//! 	Err(NeuErr::new("Error occurred internally")
52//!     	.attach(Retryable::No)
53//! 		.into())
54//! }
55//!
56//! #[macro_rules_attribute::apply(require_context)]
57//! pub fn do_something() -> Result<()> {
58//! 	// There would be a compile-time error if no context was given.
59//! 	do_something_internal().context("Operation failed")?;
60//! 	Ok(())
61//! }
62//!
63//! // In consumer/application:
64//! fn main() {
65//! 	match do_something() {
66//! 		Ok(()) => {}
67//! 		Err(err) if err.retryable() => {
68//! 			eprintln!("Retryable error");
69//! 		}
70//! 		Err(_) => {
71//! 			eprintln!("Non-retryable error");
72//! 		}
73//! 	}
74//! }
75//! ```
76//!
77//! Run `cargo add neuer-error` to add the library to your project.
78//!
79//! ## Error Formatting
80//!
81//! Error formatting is targeted towards developers. If you need to show errors to users, it is
82//! recommended to use special attachments for that ([see example](examples/non-dev-user.rs)).
83//!
84//! The error will be formatted in a "pretty" multi-line format (`{err}` or `{err:?}`):
85//!
86//! ```text
87//! Failed compiling code
88//! |- at examples/tool-cli.rs:33:23
89//! |
90//! Preprocessor failed
91//! |- at examples/tool-cli.rs:22:25
92//! |
93//! Binary gcc not found
94//! |- at examples/tool-cli.rs:17:9
95//! ```
96//!
97//! Single-line formatting can be achieved via the alternate formatting mode (`{err:#}`):
98//!
99//! ```text
100//! Failed compiling code (at examples/tool-cli.rs:33:23); Preprocessor failed (at examples/tool-cli.rs:22:25); Binary gcc not found (at examples/tool-cli.rs:17:9)
101//! ```
102//!
103//! The error can be formatted using Rust's default debug structure with alternate debug mode
104//! (`{err:#?}`).
105//!
106//! ## Comparisons
107//!
108//! ### Anyhow / Eyre
109//!
110//! - `NeuErr` provides a meechanism to discover and retrieve multiple items of typed context
111//!   information, while `anyhow` can `downcast` to its source error types only.
112//! - `NeuErr` provides a helper to ensure you don't forget to add context to your errors.
113//! - `NeuErr` captures source locations instead of backtraces by default, which is more efficient
114//!   and works without debug info. I personally also find it easier to read.
115//!
116//! ### Thiserror / Snafu
117//!
118//! - `NeuErr` is a single error type for all errors, so no need for boilerplate, better ergonomics,
119//!   but less type safety and flexibility.
120//! - `NeuErr` captures source location automatically, which `thiserror` does not and `snafu` does
121//!   only when you add the location field to every error variant.
122//! - `NeuErr` prints the full (source) error chain already.
123//! - `NeuErr` does not have procedural macros.
124//!
125//! ## Feature Flags
126//!
127//! **default** -> std, send, sync: Default selected features. Deactivate with
128//! `default-features=false`.
129//!
130//! **std** (default): Enables use of `std`. Provides interaction with `ExitCode` termination.
131//!
132//! **send** (default): Requires all contained types to be `Send`, so that [`NeuErr`] is also
133//! `Send`.
134//!
135//! **sync** (default) -> send: Requires all contained types to be `Sync`, so that [`NeuErr`] is
136//! also `Sync`.
137//!
138//! **colors**: Activates colored error formatting via `yansi` (added dependency). When std it
139//! enabled, it also enables `yansi`'s automatic detection whether to use or not use colors. See
140//! `yansi`'s documentation on details.
141#![cfg_attr(not(feature = "std"), no_std)]
142#![warn(clippy::std_instead_of_core, clippy::std_instead_of_alloc, clippy::alloc_instead_of_core)]
143
144extern crate alloc;
145
146mod error;
147mod features;
148mod macros;
149mod results;
150
151pub use self::{
152	error::{NeuErr, NeuErrImpl, ProvideContext},
153	results::{ConvertOption, ConvertResult, NeuErrResultExt, ResultExt},
154};
155
156pub mod traits {
157	//! All traits that need to be in scope for	comfortable usage.
158	pub use crate::{ConvertOption as _, ConvertResult as _, NeuErrResultExt as _, ResultExt as _};
159}
160
161/// `Result` type alias using the crate's [`NeuErr`] type.
162pub type Result<T, E = NeuErr> = ::core::result::Result<T, E>;
163
164/// Create a `Result::Ok` value with [`NeuErr`] as given error type.
165#[inline(always)]
166#[expect(non_snake_case, reason = "Mimics Result::Ok")]
167pub const fn Ok<T>(value: T) -> Result<T> {
168	Result::Ok(value)
169}
170
171#[cfg(test)]
172mod tests;