Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ All notable changes to this project will be documented in this file.

## [Unreleased]

## [0.24.17] - 2025-11-02

### Fixed
- Preserve captured backtraces when wrapping `AppError` instances through
`ResultExt::context` by sharing the snapshot instead of attempting to clone
`std::backtrace::Backtrace`.

## [0.24.16] - 2025-11-01

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

[package]
name = "masterror"
version = "0.24.16"
version = "0.24.17"
rust-version = "1.90"
edition = "2024"
license = "MIT OR Apache-2.0"
Expand Down
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ The build script keeps the full feature snippet below in sync with

~~~toml
[dependencies]
masterror = { version = "0.24.16", default-features = false }
masterror = { version = "0.24.17", default-features = false }
# or with features:
# masterror = { version = "0.24.16", features = [
# masterror = { version = "0.24.17", features = [
# "std", "axum", "actix", "openapi",
# "serde_json", "tracing", "metrics", "backtrace",
# "sqlx", "sqlx-migrate", "reqwest", "redis",
Expand Down Expand Up @@ -459,4 +459,3 @@ assert_eq!(problem.grpc.expect("grpc").name, "UNAUTHENTICATED");

MSRV: **1.90** · License: **MIT OR Apache-2.0** · No `unsafe`


57 changes: 51 additions & 6 deletions WHY_MIGRATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,10 @@ use masterror::prelude::*;
fn process() -> AppResult<()> {
ensure!(condition, AppError::bad_request("invalid input"));

// Simple context (anyhow-style)
database_call().context("db operation failed")?;

// Or structured context with metadata
database_call()
.ctx(|| Context::new(AppErrorKind::Database)
.with(field::str("table", "users"))
Expand All @@ -100,7 +104,7 @@ fn process() -> AppResult<()> {
fail!(AppError::internal("unrecoverable"));
}

// ✅ Same ergonomics as anyhow
// ✅ Same ergonomics as anyhow (.context(), .chain(), .downcast_ref())
// ✅ Plus: typed errors
// ✅ Plus: structured metadata
// ✅ Plus: automatic tracing
Expand Down Expand Up @@ -194,6 +198,32 @@ let err = AppError::database("query failed")
// ✅ Zero boilerplate
```

#### 5. Error Introspection (anyhow Parity)

```rust
// anyhow: type-safe error inspection
if let Some(io_err) = err.downcast_ref::<io::Error>() {
match io_err.kind() {
io::ErrorKind::NotFound => /* handle */,
_ => /* other */
}
}

// masterror: same API, works with AppError
use masterror::ResultExt;

match database_op().context("db failed") {
Err(err) => {
if let Some(io_err) = err.downcast_ref::<io::Error>() {
// ✅ Type-safe downcasting
// ✅ Inspect wrapped error sources
// ✅ Full anyhow API compatibility
}
}
Ok(val) => val
}
```

## Migration Guide

### From thiserror
Expand Down Expand Up @@ -243,18 +273,29 @@ bail!("invalid input");
fail!(AppError::bad_request("invalid input"));
```

**Step 3:** Enhance context
**Step 3:** Keep using .context() (it just works!)
```rust
// Before
// Before (anyhow)
.context("db error")?

// After
// After (masterror) - identical API
.context("db error")?

// Or use structured context for better observability
.ctx(|| Context::new(AppErrorKind::Database)
.with(field::str("table", "users"))
)?
```

**Result:** Type-safe, structured, observable errors.
**Step 4:** Error introspection works the same
```rust
// anyhow API still works
if let Some(io_err) = err.downcast_ref::<io::Error>() {
// handle specific error type
}
```

**Result:** Type-safe, structured, observable errors with zero API friction.

## Real-World Impact

Expand Down Expand Up @@ -346,7 +387,11 @@ Binary size: 944KB (vs thiserror 32KB, anyhow 566KB)

- 📚 [Full Documentation](https://docs.rs/masterror)
- 📊 [Benchmarks](BENCHMARKS.md)
- 🔧 [Examples](examples/)
- 🔧 **[Examples](examples/)** - See working code for:
- [Basic Usage](examples/basic_usage.rs) - Core error handling patterns
- [thiserror Compatibility](examples/derive_error.rs) - Drop-in replacement
- [Structured Metadata](examples/structured_metadata.rs) - Typed fields vs strings
- [Redaction](examples/redaction.rs) - GDPR-compliant privacy controls
- 💬 [GitHub Issues](https://github.com/RAprogramm/masterror/issues)

---
Expand Down
19 changes: 19 additions & 0 deletions examples/redaction.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// SPDX-FileCopyrightText: 2025 RAprogramm <andrey.rozanov.vl@gmail.com>
//
// SPDX-License-Identifier: MIT

//! Redaction example showing GDPR-compliant field masking.

use masterror::{AppError, FieldRedaction, field};

fn main() {
let err = AppError::bad_request("Invalid credentials")
.with_field(field::str("email", "user@example.com").with_redaction(FieldRedaction::Hash))
.with_field(field::str("ip", "192.168.1.100").with_redaction(FieldRedaction::Redact))
.with_field(field::str("session_id", "abc123"));

println!("=== Redacted Metadata ===\n");
for (key, value, redaction) in err.metadata().iter_with_redaction() {
println!("{key}: {value:?} [{redaction:?}]");
}
}
41 changes: 34 additions & 7 deletions src/app_error/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,9 @@ pub struct ErrorInner {
pub details: Option<String>,
pub source: Option<Arc<dyn CoreError + Send + Sync + 'static>>,
#[cfg(feature = "backtrace")]
pub backtrace: Option<Backtrace>,
pub backtrace: Option<Arc<Backtrace>>,
#[cfg(feature = "backtrace")]
pub captured_backtrace: OnceLock<Option<Backtrace>>,
pub captured_backtrace: OnceLock<Option<Arc<Backtrace>>>,
telemetry_dirty: AtomicBool,
#[cfg(feature = "tracing")]
tracing_dirty: AtomicBool
Expand All @@ -110,9 +110,9 @@ const BACKTRACE_STATE_DISABLED: u8 = 2;
static BACKTRACE_STATE: AtomicU8 = AtomicU8::new(BACKTRACE_STATE_UNSET);

#[cfg(feature = "backtrace")]
fn capture_backtrace_snapshot() -> Option<Backtrace> {
fn capture_backtrace_snapshot() -> Option<Arc<Backtrace>> {
if should_capture_backtrace() {
Some(Backtrace::capture())
Some(Arc::new(Backtrace::capture()))
} else {
None
}
Expand Down Expand Up @@ -321,13 +321,13 @@ impl Error {

#[cfg(feature = "backtrace")]
fn capture_backtrace(&self) -> Option<&CapturedBacktrace> {
if let Some(backtrace) = self.backtrace.as_ref() {
if let Some(backtrace) = self.backtrace.as_deref() {
return Some(backtrace);
}

self.captured_backtrace
.get_or_init(capture_backtrace_snapshot)
.as_ref()
.as_deref()
}

#[cfg(not(feature = "backtrace"))]
Expand All @@ -336,7 +336,7 @@ impl Error {
}

#[cfg(feature = "backtrace")]
fn set_backtrace_slot(&mut self, backtrace: CapturedBacktrace) {
fn set_backtrace_slot(&mut self, backtrace: Arc<Backtrace>) {
self.backtrace = Some(backtrace);
self.captured_backtrace = OnceLock::new();
}
Expand Down Expand Up @@ -574,6 +574,21 @@ impl Error {
/// Attach a captured backtrace.
#[must_use]
pub fn with_backtrace(mut self, backtrace: CapturedBacktrace) -> Self {
#[cfg(feature = "backtrace")]
{
self.set_backtrace_slot(Arc::new(backtrace));
}

#[cfg(not(feature = "backtrace"))]
{
self.set_backtrace_slot(backtrace);
}
self.mark_dirty();
self
}

#[cfg(feature = "backtrace")]
pub(crate) fn with_shared_backtrace(mut self, backtrace: Arc<Backtrace>) -> Self {
self.set_backtrace_slot(backtrace);
self.mark_dirty();
self
Expand Down Expand Up @@ -678,6 +693,18 @@ impl Error {
self.capture_backtrace()
}

#[cfg(feature = "backtrace")]
pub(crate) fn backtrace_shared(&self) -> Option<Arc<Backtrace>> {
if let Some(backtrace) = self.backtrace.as_ref() {
return Some(Arc::clone(backtrace));
}

self.captured_backtrace
.get_or_init(capture_backtrace_snapshot)
.as_ref()
.map(Arc::clone)
}

/// Borrow the source if present.
#[must_use]
pub fn source_ref(&self) -> Option<&(dyn CoreError + Send + Sync + 'static)> {
Expand Down
Loading
Loading