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