Table of Contents
- Overview
- Highlights
- Workspace Crates
- Feature Flags
- Installation
- Benchmarks
- Code Coverage
- Quick Start
- Advanced Usage
- Examples
- Resources
- Metrics
- License
Overview
masterror grew from a handful of helpers into a workspace of composable crates for
building consistent, observable error surfaces across Rust services. The core
crate stays framework-agnostic, while feature flags light up transport adapters,
integrations and telemetry without pulling in heavyweight defaults. No
unsafe, MSRV is pinned, and the derive macros keep your domain types in charge
of redaction and metadata.
Highlights
- Unified taxonomy.
AppError,AppErrorKindandAppCodemodel domain and transport concerns with conservative HTTP/gRPC mappings, turnkey retry/auth hints and RFC7807 output viaProblemJson. - Native derives.
#[derive(Error)],#[derive(Masterror)],#[app_error],#[masterror(...)]and#[provide]wire custom types intoAppErrorwhile forwarding sources, backtraces, telemetry providers and redaction policy. - Typed telemetry.
Metadatastores structured key/value context (strings, integers, floats, durations, IP addresses and optional JSON) with per-field redaction controls and builders infield::*, so logs stay structured without manualStringmaps. - Transport adapters. Optional features expose Actix/Axum responders,
tonic::Statusconversions, WASM/browser logging and OpenAPI schema generation without contaminating the lean default build. - Battle-tested integrations. Enable focused mappings for
sqlx,reqwest,redis,validator,config,tokio,teloxide,multipart, Telegram WebApp SDK and more — each translating library errors into the taxonomy with telemetry attached. - Turnkey defaults. The
turnkeymodule ships a ready-to-use error catalog, helper builders and tracing instrumentation for teams that want a consistent baseline out of the box. - Typed control-flow macros.
ensure!andfail!short-circuit functions with your domain errors without allocating or formatting on the happy path.
Workspace Crates
| Crate | What it provides | When to depend on it |
|---|---|---|
masterror |
Core error types, metadata builders, transports, integrations and the prelude. | Application crates, services and libraries that want a stable error surface. |
masterror-derive |
Proc-macros backing #[derive(Error)], #[derive(Masterror)], #[app_error] and #[provide]. |
Brought in automatically via masterror; depend directly only for macro hacking. |
masterror-template |
Shared template parser used by the derive macros for formatter analysis. | Internal dependency; reuse when you need the template parser elsewhere. |
Feature Flags
Pick only what you need; everything is off by default.
- Web transports:
axum,actix,multipart,openapi,serde_json. - Telemetry & observability:
tracing,metrics,backtrace,coloredfor colored terminal output. - Async & IO integrations:
tokio,reqwest,sqlx,sqlx-migrate,redis,validator,config. - Messaging & bots:
teloxide,telegram-webapp-sdk. - Front-end tooling:
frontendfor WASM/browser console logging. - gRPC:
tonicto emittonic::Statusresponses. - Batteries included:
turnkeyto adopt the pre-built taxonomy and helpers.
The build script keeps the full feature snippet below in sync with
Cargo.toml.
Installation
[]
= { = "0.25.1", = false }
# or with features:
# masterror = { version = "0.25.1", features = [
# "std", "axum", "actix", "openapi",
# "serde_json", "tracing", "metrics", "backtrace",
# "colored", "sqlx", "sqlx-migrate", "reqwest",
# "redis", "validator", "config", "tokio",
# "multipart", "teloxide", "telegram-webapp-sdk", "tonic",
# "frontend", "turnkey", "benchmarks"
# ] }
Benchmarks
Criterion benchmarks cover the hottest conversion paths so regressions are visible before shipping. Run them locally with:
The suite emits two groups:
context_into_error/*promotes a dummy source error with representative metadata (strings, counters, durations, IPs) throughContext::into_errorin both redacted and non-redacted modes.problem_json_from_app_error/*consumes the resultingAppErrorvalues to build RFC 7807 payloads viaProblemJson::from_app_error, showing how message redaction and field policies impact serialization.
Adjust Criterion CLI flags (for example --sample-size 200 or --save-baseline local) after -- to trade
throughput for tighter confidence intervals when investigating changes.
Code Coverage
Coverage reports are automatically generated on every CI run and uploaded to Codecov. The project maintains high test coverage across all modules to ensure reliability and catch regressions early.
Sunburst Graph
The inner-most circle represents the entire project, moving outward through folders to individual files. Size and color indicate statement count and coverage percentage.
Grid View
Each block represents a single file. Block size and color correspond to statement count and coverage percentage.
Icicle Chart
Hierarchical view starting with the entire project at the top, drilling down through folders to individual files. Size and color reflect statement count and coverage.
Quick Start
Create an error:
use ;
let err = new;
assert!;
let err_with_meta = service
.with_field;
assert_eq!;
let err_with_context = internal
.with_context;
assert!;
With prelude:
use *;
Advanced Usage
ensure! and fail! provide typed alternatives to the formatting-heavy
anyhow::ensure!/anyhow::bail! helpers. They evaluate the error expression
only when the guard trips, so success paths stay allocation-free.
use ;
assert!;
assert!;
assert!;
masterror ships native derives so your domain types stay expressive while the
crate handles conversions, telemetry and redaction for you.
use io;
use Error;
;
let err = load.unwrap_err;
assert_eq!;
let wrapped = from;
assert_eq!;
use masterror::Error;brings the derive macro into scope.#[from]automatically implementsFrom<...>while ensuring wrapper shapes are valid.#[error(transparent)]enforces single-field wrappers that forwardDisplay/sourceto the inner error.#[app_error(kind = AppErrorKind::..., code = AppCode::..., message)]maps the derived error intoAppError/AppCode. The optionalcode = ...arm emits anAppCodeconversion, while themessageflag forwards the derivedDisplayoutput as the public message instead of producing a bare error.masterror::error::template::ErrorTemplateparses#[error("...")]strings, exposing literal and placeholder segments so custom derives can be implemented without relying onthiserror.TemplateFormattermirrorsthiserror's formatter detection so existing derives that relied on hexadecimal, pointer or exponential renderers keep compiling.- Display placeholders preserve their raw format specs via
TemplateFormatter::display_spec()andTemplateFormatter::format_fragment(), so derived code can forward:>8,:.3and other display-only options without reconstructing the original string. TemplateFormatterKindexposes the formatter trait requested by a placeholder, making it easy to branch on the requested rendering behaviour without manually matching every enum variant.
#[derive(Masterror)] wires a domain error into [masterror::Error], adds
metadata, redaction policy and optional transport mappings. The accompanying
#[masterror(...)] attribute mirrors the #[app_error] syntax while staying
explicit about telemetry and redaction.
use ;
let err = MissingFlag ;
let converted: Error = err.into;
assert_eq!;
assert_eq!;
assert_eq!;
assert!;
assert_eq!;
code/categorypick the public [AppCode] and internal [AppErrorKind].messageforwards the formatted [Display] output as the safe public message. Omit it to keep the message private.redact(message)flips [MessageEditPolicy] to redactable at the transport boundary,fields("name" = hash, "card" = last4)overrides metadata policies (hash,last4,redact,none).telemetry(...)accepts expressions that evaluate toOption<masterror::Field>. Each populated field is inserted into the resulting [Metadata]; usetelemetry()when no fields are attached.map.grpc/map.problemcapture optional gRPC status codes (asi32) and RFC 7807typeURIs. The derive emits tables such asMyError::HTTP_MAPPING,MyError::GRPC_MAPPINGandMyError::PROBLEM_MAPPING(or slice variants for enums) for downstream integrations.
All familiar field-level attributes (#[from], #[source], #[backtrace])
are still honoured. Sources and backtraces are automatically attached to the
generated [masterror::Error].
#[provide(...)] exposes typed context through std::error::Request, while
#[app_error(...)] records how your domain error translates into AppError
and AppCode. The derive mirrors thiserror's syntax and extends it with
optional telemetry propagation and direct conversions into the masterror
runtime types.
use request_ref;
use ;
let err = StructuredTelemetryError ;
let snapshot = .expect;
assert_eq!;
let app: AppError = err.into;
let via_app = .expect;
assert_eq!;
Optional telemetry only surfaces when present, so None does not register a
provider. Owned snapshots can still be provided as values when the caller
requests ownership:
use ;
let noisy = OptionalTelemetryError ;
let silent = OptionalTelemetryError ;
assert!;
assert!;
Enums support per-variant telemetry and conversion metadata. Each variant chooses
its own AppErrorKind/AppCode mapping while the derive generates a single
From<Enum> implementation:
let owned = Owned;
let app: AppError = owned.into;
assert!;
Compared to thiserror, you retain the familiar deriving surface while gaining
structured telemetry (#[provide]) and first-class conversions into
AppError/AppCode without manual glue.
use ;
use Duration;
let problem = from_app_error;
assert_eq!;
assert_eq!;
assert_eq!;
The DisplayMode API lets you control error output formatting based on deployment
environment without changing your error handling code. Three modes are available:
-
DisplayMode::Prod— Lightweight JSON output with minimal fields, optimized for production logs. Only includeskind,code, andmessage(if not redacted). Filters sensitive metadata automatically. -
DisplayMode::Local— Human-readable multi-line output with full context. Shows error details, complete source chain, all metadata, and backtrace (if enabled). Best for local development and debugging. -
DisplayMode::Staging— JSON output with additional context. Includeskind,code,message, limitedsource_chain, and filtered metadata. Useful for staging environments where you need structured logs with more detail.
Automatic Environment Detection:
The mode is auto-detected in this order:
MASTERROR_ENVenvironment variable (prod,local, orstaging)KUBERNETES_SERVICE_HOSTpresence (triggersProdmode)- Build configuration (
debug_assertions→Local, release →Prod)
The result is cached on first access for zero-cost subsequent calls.
use DisplayMode;
// Query the current mode (cached after first call)
let mode = current;
match mode
Colored Terminal Output:
Enable the colored feature for enhanced terminal output in local mode:
[]
= { = "0.25.1", = ["colored"] }
With colored enabled, errors display with syntax highlighting:
- Error kind and code in bold
- Error messages in color
- Source chain with indentation
- Metadata keys highlighted
use ;
let error = not_found
.with_field
.with_field;
// Without 'colored': plain text
// With 'colored': color-coded output in terminals
println!;
Production vs Development Output:
Without colored feature, errors display their AppErrorKind label:
NotFound
With colored feature, full multi-line format with context:
Error: NotFound
Code: NOT_FOUND
Message: User not found
Context:
user_id: 12345
request_id: abc-def
This separation keeps production logs clean while giving developers rich context during local debugging sessions.
Examples
Comprehensive real-world examples demonstrating masterror integration with popular frameworks:
| Example | Description | Features |
|---|---|---|
| axum-rest-api | REST API with RFC 7807 Problem Details | HTTP endpoints, domain errors, integration tests |
| sqlx-database | Database error handling with SQLx | Connection errors, constraint violations, transactions |
| custom-domain-errors | Payment processing domain errors | Derive macro, error conversion, structured errors |
| basic-async | Async error handling with tokio | Error propagation, timeout handling, Result types |
All examples are runnable and include comprehensive tests. See the examples/ directory for complete source code and documentation.
Resources
- Explore the error-handling wiki for step-by-step guides,
comparisons with
thiserror/anyhow, and troubleshooting recipes. - Browse the crate documentation on docs.rs for API details, feature-specific guides and transport tables.
- Check
CHANGELOG.mdfor release highlights and migration notes. - Review RustManifest for the development standards and best practices this project follows.
Metrics
License
MSRV: 1.90 · License: MIT · No unsafe