error_forge/lib.rs
1//! # Error Forge
2//!
3//! Error Forge is a pragmatic Rust error-handling crate for applications that need
4//! structured metadata, readable output, and operational hooks without forcing a
5//! single application architecture.
6//!
7//! It provides:
8//!
9//! - [`ForgeError`] for stable error metadata
10//! - [`AppError`] for immediate use in small and medium projects
11//! - [`define_errors!`] for declarative custom enums
12//! - [`group!`] for coarse-grained composition
13//! - optional derive support with `#[derive(ModError)]`
14//! - context wrapping, error codes, collectors, logging hooks, and console formatting
15//! - synchronous retry and circuit-breaker helpers in [`recovery`]
16//!
17//! ## Messages for users and for logs
18//!
19//! [`ForgeError::user_message`] is safe to show end users: by default it
20//! is the error's caption and never carries the error's data. `Display`,
21//! `Debug` and [`ForgeError::dev_message`] carry everything the error
22//! holds (paths, endpoints, source errors, field values), so keep them
23//! for logs, and wrap secrets in [`Redacted`] so they print as
24//! `[redacted]` even there.
25//!
26//! ## Quick Start
27//!
28//! ```
29//! use error_forge::{define_errors, ForgeError};
30//!
31//! define_errors! {
32//! pub enum ServiceError {
33//! #[error(display = "Configuration error: {message}", message)]
34//! #[kind(Config, status = 500)]
35//! Config { message: String },
36//!
37//! #[error(display = "Request to {endpoint} failed", endpoint)]
38//! #[kind(Network, retryable = true, status = 503)]
39//! Network { endpoint: String },
40//! }
41//! }
42//!
43//! let error = ServiceError::config("Missing DATABASE_URL".to_string());
44//! assert_eq!(error.kind(), "Config");
45//! ```
46//!
47//! ## Built-in Formatting
48//!
49//! ```
50//! use error_forge::{console_theme::print_error, AppError};
51//!
52//! let error = AppError::config("Database connection failed");
53//! print_error(&error);
54//! ```
55
56#![forbid(unsafe_code)]
57pub mod collector;
58pub mod console_theme;
59pub mod context;
60pub mod error;
61pub mod group_macro;
62pub mod logging;
63pub mod macros;
64pub mod recovery;
65mod redacted;
66pub mod registry;
67
68#[cfg(feature = "async")]
69pub mod async_error;
70#[cfg(feature = "async")]
71pub mod async_error_impl;
72
73// Re-export core types and traits
74pub use crate::console_theme::{install_panic_hook, print_error, ConsoleTheme};
75pub use crate::error::{AppError, AppResult, ForgeError};
76pub use crate::redacted::Redacted;
77
78// Historical re-export. `Result` shadows `std::result::Result` in
79// glob imports; deprecated in favour of `AppResult`. Kept for
80// source compatibility through the `1.x` line.
81#[allow(deprecated)]
82pub use crate::error::Result;
83
84// Re-export context module
85pub use crate::context::{ContextError, ResultExt};
86
87// Re-export registry module
88pub use crate::registry::{
89 register_error_code, CodedError, ErrorCodeInfo, ErrorRegistry, WithErrorCode,
90};
91
92// Re-export collector module
93pub use crate::collector::{CollectError, ErrorCollector};
94
95// Re-export logging module
96pub use crate::logging::{log_error, logger, register_logger, ErrorLogger};
97
98// Re-export async module (when enabled)
99#[cfg(feature = "async")]
100pub use crate::async_error::{AsyncForgeError, AsyncResult};
101
102// Re-export hook types from `macros` — explicitly named so the
103// public surface stays under our control. `define_errors!` and
104// `group!` are re-exported automatically because they are
105// `#[macro_export]`'d.
106#[allow(deprecated)]
107pub use crate::macros::{
108 register_error_hook, try_register_error_hook, ErrorContext, ErrorLevel, ErrorSource,
109};
110
111// Optional re-export of the proc macro
112#[cfg(feature = "derive")]
113pub use error_forge_derive::ModError;
114
115/// Internal re-exports for use by macros expanded in user crates.
116///
117/// This module is not part of the public API. Items here may
118/// change at any time without notice. They are exposed only so
119/// that `define_errors!` (and other macros that expand into user
120/// code) can reference dependencies through `$crate::__private::*`
121/// without forcing every user to add those crates to their own
122/// `Cargo.toml`.
123#[doc(hidden)]
124pub mod __private {
125 pub use error_forge_derive::__paste as paste;
126}
127
128// Extension methods are implemented in error.rs
129
130/// Runs every `rust` code block in `docs/API.md` as a doctest so the
131/// narrative reference cannot drift from the API. Several examples use
132/// `#[derive(ModError)]` and `AsyncForgeError`, so this only builds when
133/// both features are on (CI runs `cargo test --all-features`).
134#[cfg(all(doctest, feature = "derive", feature = "async"))]
135#[doc = include_str!("../docs/API.md")]
136pub struct ApiReferenceDoctests;
137
138/// Runs every `rust` code block in `README.md` as a doctest. The derive
139/// example needs the `derive` feature. Doctests are compiled with this
140/// crate's features as `cfg`s, so with `serde` on, the `serde` derive
141/// that `define_errors!` adds would also apply to the README enums,
142/// whose `source` fields are not serializable; the README is checked by
143/// the feature combinations without `serde` instead.
144#[cfg(all(doctest, feature = "derive", not(feature = "serde")))]
145#[doc = include_str!("../README.md")]
146pub struct ReadmeDoctests;
147
148#[cfg(test)]
149mod tests {
150 use crate::ForgeError;
151
152 #[test]
153 fn test_error_display() {
154 let err = crate::error::AppError::config("Test error");
155 assert!(err.to_string().contains("Test error"));
156 }
157
158 #[test]
159 fn test_error_kind() {
160 let err = crate::error::AppError::config("Test error");
161 assert_eq!(err.kind(), "Config");
162 }
163}