1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! A typed error system with error stacks and source-code location tracking.
//!
//! The crate provides the [`ErrorStack`] trait, which extends
//! [`std::error::Error`] with two methods:
//! [`stack_source`](ErrorStack::stack_source) returning the next typed
//! link in the error chain, and [`location`](ErrorStack::location)
//! returning the source-code location where the error was constructed.
//!
//! The trait is mainly used via `#[derive(ErrorStack)]`, which implements
//! [`ErrorStack`] based on field names and attributes. The macro also
//! generates helper constructors that automatically capture the call-site
//! location, and when a source field is present return a closure allowing
//! ergonomic chaining with [`Result::map_err`].
//!
//! An [`ErrorStack`] can be converted into a [`Report`], which walks the
//! full typed chain and produces a traceback with source-code locations.
//!
//! # Motivation
//!
//! [`Error::source`](std::error::Error::source) only exposes causes as
//! `&dyn Error`, so concrete types and any extra context they carry are
//! lost. Backtraces show where code was running, not where errors were
//! constructed. `errorstack` fills this gap by recording the source-code
//! location of each error and preserving the full typed chain, so every
//! cause and its origin are available for inspection or display.
//!
//! # Quick start
//!
//! ```
//! use errorstack::{ErrorStack, Report};
//!
//! #[derive(thiserror::Error, ErrorStack, Debug)]
//! pub enum AppError {
//! #[error("io failed: {path}")]
//! Io {
//! path: String,
//! source: std::io::Error,
//! #[location]
//! location: &'static std::panic::Location<'static>,
//! },
//!
//! #[error("config failed")]
//! Config {
//! #[stack_source]
//! source: ConfigError,
//! #[location]
//! location: &'static std::panic::Location<'static>,
//! },
//! }
//!
//! #[derive(thiserror::Error, ErrorStack, Debug)]
//! #[error("invalid config: {detail}")]
//! pub struct ConfigError {
//! detail: String,
//! #[location]
//! location: &'static std::panic::Location<'static>,
//! }
//!
//! fn load_config() -> Result<(), AppError> {
//! let inner = ConfigError::new("missing field `port`".into());
//! Err(AppError::config(inner))
//! }
//!
//! let err = load_config().unwrap_err();
//! let report = Report::new(&err);
//! assert_eq!(report.entries().count(), 2);
//! ```
//!
//! Printing `report` produces output similar to:
//!
//! ```text
//! Error: config failed
//! at src/main.rs:14:9
//!
//! Caused by this error:
//! 1: invalid config: missing field `port`
//! at src/main.rs:13:17
//! ```
//!
//! # Core concepts
//!
//! ## The [`ErrorStack`] trait
//!
//! [`ErrorStack`] extends [`Error`](std::error::Error) with two methods:
//!
//! - [`location`](ErrorStack::location) returns the
//! [`std::panic::Location`] where the error was constructed, or [`None`]
//! if location tracking is not present for that error.
//!
//! - [`stack_source`](ErrorStack::stack_source) returns the next
//! [`ErrorStack`] implementor in the chain, or [`None`] if the error is
//! the root cause or if the underlying source does not implement
//! [`ErrorStack`].
//!
//! The trait is typically derived rather than implemented by hand. See the
//! [derive macro documentation](derive@ErrorStack) for the full attribute
//! reference, naming conventions, and generated constructor signatures.
//!
//! ## [`Report`]
//!
//! [`Report`] collects an entire error chain into a list of [`Entry`]
//! values, each pairing an error message with a source-code
//! location where available.
//!
//! [`Report`] provides a default [`Display`](std::fmt::Display)
//! implementation that renders the chain in a human-readable format with
//! the outermost error first, followed by numbered causes and their
//! locations. Callers that need a different structure (for example,
//! emitting each frame as a structured telemetry event) can iterate over
//! the [`Entry`] values directly via [`Report::entries`].
//!
//! # Optional sources
//!
//! A source field may be `Option<T>` when an error does not always have an
//! underlying cause. The derive macro generates two constructors in this
//! case: one that sets the source to [`None`], and a `_with` variant that
//! accepts the inner error and wraps it in [`Some`]. See the
//! [derive macro documentation](derive@ErrorStack#optional-sources) for
//! details.
//!
//! ```
//! use errorstack::ErrorStack;
//!
//! #[derive(thiserror::Error, ErrorStack, Debug)]
//! #[error("lookup failed: {key}")]
//! pub struct LookupError {
//! key: String,
//! source: Option<std::io::Error>,
//! #[location]
//! location: &'static std::panic::Location<'static>,
//! }
//!
//! let err = LookupError::new("missing-key".into());
//!
//! # fn try_lookup() -> Result<(), LookupError> {
//! let _data = std::fs::read_to_string("db.json")
//! .map_err(LookupError::new_with("db-key".into()))?;
//! # Ok(())
//! # }
//! ```
//!
//! # Compatibility with `thiserror`
//!
//! `errorstack` uses the same field conventions as
//! [`thiserror`](https://crates.io/crates/thiserror) and is designed to
//! pair with it.
pub use ErrorStack;
/// An error within a typed error stack, preserving full error context as
/// errors propagate up the call stack.
///
/// Each error may carry the source-code [`location`] where it was constructed
/// and a reference to the next error in the stack via [`stack_source`].
///
/// Typically derived via `#[derive(ErrorStack)]` rather than implemented by
/// hand.
///
/// # Examples
///
/// ```
/// use errorstack::ErrorStack;
///
/// #[derive(thiserror::Error, ErrorStack, Debug)]
/// #[error("leaf error")]
/// struct LeafError {
/// #[location]
/// location: &'static std::panic::Location<'static>,
/// }
///
/// let err = LeafError::new();
/// assert!(err.location().is_some());
/// ```
///
/// [`stack_source`]: ErrorStack::stack_source
/// [`location`]: ErrorStack::location
/// A single entry in an error report, pairing an error message with an
/// optional source-code [`Location`].
///
/// Entries are produced by [`Report::new`] and accessed via
/// [`Report::entries`] or [`Report::iter`].
///
/// # Examples
///
/// ```
/// use errorstack::{ErrorStack, Report};
///
/// #[derive(thiserror::Error, ErrorStack, Debug)]
/// #[error("something broke")]
/// struct MyError {
/// #[location]
/// location: &'static std::panic::Location<'static>,
/// }
///
/// let report = Report::new(&MyError::new());
/// let messages: Vec<_> = report.iter().map(|e| e.message()).collect();
/// assert_eq!(messages, ["something broke"]);
/// ```
///
/// [`Location`]: std::panic::Location
/// A collected summary of an entire error chain, suitable for display or
/// structured inspection.
///
/// `Report` walks the typed [`ErrorStack::stack_source`] chain to extract
/// source-code locations, then falls back to [`Error::source`] to capture
/// any remaining non-[`ErrorStack`] causes.
///
/// # Examples
///
/// ```
/// # use std::error::Error;
/// # use errorstack::{ErrorStack, Report};
/// # use std::fmt;
/// #
/// # #[derive(Debug)]
/// # struct RootError;
/// # impl fmt::Display for RootError {
/// # fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
/// # write!(f, "root cause")
/// # }
/// # }
/// # impl Error for RootError {}
/// # impl ErrorStack for RootError {
/// # fn location(&self) -> Option<&'static std::panic::Location<'static>> { None }
/// # }
/// #
/// let err = RootError;
/// let report = Report::new(&err);
/// println!("{report}");
/// ```
///
/// [`Error::source`]: std::error::Error::source