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
//! Extension traits for errors and results.
use std::fmt::{Debug, Display};
use crate::annotation::{IntoMessage, IntoSuggestion};
use crate::error::{Error, Whatever};
use crate::report::Report;
use crate::value::Value;
/// Extension trait for bare errors.
pub trait ErrorExt: Error + Sized {
/// Wrap this error in a [`Report`].
fn report(self) -> Report<Self>;
/// Escalate this error directly into a differently-typed report.
fn escalate<F: Error>(self, error: F) -> Report<F>;
/// Convert this error into a freeform [`Whatever`] report.
///
/// # Panics
///
/// Does not panic; the description is required so there is no way to construct a
/// report without one.
fn whatever<F: Whatever>(self, description: impl IntoMessage) -> Report<F>;
/// Convert this error into a freeform [`Whatever`] report with a lazily computed
/// description.
fn whatever_with<F, M>(self, description: impl FnOnce(&Self) -> M) -> Report<F>
where
F: Whatever,
M: IntoMessage;
}
impl<E: Error> ErrorExt for E {
#[track_caller]
fn report(self) -> Report<Self> {
Report::new(self)
}
#[track_caller]
fn escalate<F: Error>(self, error: F) -> Report<F> {
self.report().escalate(error)
}
#[track_caller]
fn whatever<F: Whatever>(self, description: impl IntoMessage) -> Report<F> {
let new_error = F::from_error(&self);
self.report().escalate(new_error).message(description)
}
#[track_caller]
fn whatever_with<F, M>(self, description: impl FnOnce(&Self) -> M) -> Report<F>
where
F: Whatever,
M: IntoMessage,
{
let description = description(&self);
self.whatever(description)
}
}
/// Extension trait for results, implemented both for `Result<T, E>` and for
/// `Result<T, Report<E>>`. Every method returns `Result<T, Report<Err>>`, which is a new
/// type for the former and simply `Self` for the latter.
pub trait ResultExt<T, Err: Error> {
/// Wrap the error, if any, in a [`Report`].
///
/// # Errors
///
/// Returns `Err` exactly when `self` was `Err`.
fn report(self) -> Result<T, Report<Err>>;
/// Escalate the error, if any, into a differently-typed report.
///
/// # Errors
///
/// Returns `Err` exactly when `self` was `Err`.
fn escalate<F: Error>(self, error: F) -> Result<T, Report<F>>;
/// Convert the error, if any, into a freeform [`Whatever`] report.
///
/// # Errors
///
/// Returns `Err` exactly when `self` was `Err`.
fn whatever<F: Whatever>(self, description: impl IntoMessage) -> Result<T, Report<F>>;
/// Convert the error, if any, into a freeform [`Whatever`] report with a lazily
/// computed description.
///
/// # Errors
///
/// Returns `Err` exactly when `self` was `Err`.
fn whatever_with<F, M>(self, description: impl FnOnce(&Err) -> M) -> Result<T, Report<F>>
where
F: Whatever,
M: IntoMessage;
/// Add a message to the report, if any.
///
/// # Errors
///
/// Returns `Err` exactly when `self` was `Err`.
fn message(self, message: impl IntoMessage) -> Result<T, Report<Err>>;
/// Add a suggestion to the report, if any.
///
/// # Errors
///
/// Returns `Err` exactly when `self` was `Err`.
fn suggestion(self, suggestion: impl IntoSuggestion) -> Result<T, Report<Err>>;
/// Attach a public field to the report, if any.
///
/// # Errors
///
/// Returns `Err` exactly when `self` was `Err`.
fn field(self, key: impl Into<String>, value: impl Into<Value>) -> Result<T, Report<Err>>;
/// Same as [`ResultExt::field`], formatting `value` with [`Display`].
///
/// # Errors
///
/// Returns `Err` exactly when `self` was `Err`.
fn field_display(self, key: impl Into<String>, value: impl Display) -> Result<T, Report<Err>>;
/// Same as [`ResultExt::field`], formatting `value` with [`Debug`].
///
/// # Errors
///
/// Returns `Err` exactly when `self` was `Err`.
fn field_debug(self, key: impl Into<String>, value: impl Debug) -> Result<T, Report<Err>>;
/// Log the report at error level, if any, and return the value.
///
/// The rendered report is the event's message; `error.type` and `error.code` (when
/// the error has one) are attached as separate `tracing` fields, so a structured
/// subscriber can filter or group on them without parsing the message text.
fn log_error(self) -> Option<T>;
/// Log the report at warning level, if any, and return the value.
///
/// See [`ResultExt::log_error`] for exactly which fields are attached.
fn log_warning(self) -> Option<T>;
/// Log the report at info level, if any, and return the value.
///
/// See [`ResultExt::log_error`] for exactly which fields are attached.
fn log_info(self) -> Option<T>;
/// Log the report at error level, if any, and discard the value.
fn ignore(self);
/// Unwrap the value, treating an error as a bug in the program rather than an
/// external failure.
///
/// Only use this where an error genuinely indicates a bug, e.g., an invariant a
/// caller already checked, never for errors that can legitimately happen, e.g., I/O.
/// `invariant` documents that assumption, e.g., `"config was already validated
/// during startup"`; like [`Report::message`](crate::Report::message), it accepts a
/// plain string or a closure, evaluated lazily only if `self` was actually `Err`.
///
/// # Panics
///
/// Panics, showing `invariant` and the full rendered report, if `self` was `Err`.
/// Escalates the original report first, so the panic shows this call's own location
/// and backtrace (where the assumption was made) with the original report nested
/// underneath as its cause (where the failure actually happened) — both are usually
/// needed to debug a violated invariant. If left uncaught, this prints just that
/// rendered text to stderr, not the default panic hook's own "thread panicked at"
/// banner and (with `RUST_BACKTRACE` set) its separate, unfiltered backtrace, which
/// would otherwise show up redundantly right next to the ones already inside the
/// rendered report.
fn assert_ok(self, invariant: impl IntoMessage) -> T;
}
impl<T, E: Error> ResultExt<T, E> for Result<T, E> {
#[track_caller]
fn report(self) -> Result<T, Report<E>> {
// Not `self.map_err(Report::new)`: a `#[track_caller]` function loses caller
// tracking when passed through `map_err`'s generic `FnOnce`, since the call
// happens inside `map_err`'s own body, not literally at this call site. Calling
// it directly in a `match` arm keeps the caller's location correct (verified
// against a real caller, not just by inspection).
match self {
Ok(value) => Ok(value),
Err(error) => Err(Report::new(error)),
}
}
#[track_caller]
fn escalate<F: Error>(self, error: F) -> Result<T, Report<F>> {
match self {
Ok(value) => Ok(value),
Err(error_value) => Err(error_value.escalate(error)),
}
}
#[track_caller]
fn whatever<F: Whatever>(self, description: impl IntoMessage) -> Result<T, Report<F>> {
match self {
Ok(value) => Ok(value),
Err(error) => Err(error.whatever(description)),
}
}
#[track_caller]
fn whatever_with<F, M>(self, description: impl FnOnce(&E) -> M) -> Result<T, Report<F>>
where
F: Whatever,
M: IntoMessage,
{
match self {
Ok(value) => Ok(value),
Err(error) => Err(error.whatever_with(description)),
}
}
#[track_caller]
fn message(self, message: impl IntoMessage) -> Result<T, Report<E>> {
match self.report() {
Ok(value) => Ok(value),
Err(report) => Err(report.message(message)),
}
}
#[track_caller]
fn suggestion(self, suggestion: impl IntoSuggestion) -> Result<T, Report<E>> {
match self.report() {
Ok(value) => Ok(value),
Err(report) => Err(report.suggestion(suggestion)),
}
}
#[track_caller]
fn field(self, key: impl Into<String>, value: impl Into<Value>) -> Result<T, Report<E>> {
// `Report::field` never reads the caller's location, so `map_err` is fine here;
// only `self.report()`, which does, needs this function itself tracked.
self.report().map_err(|report| report.field(key, value))
}
#[track_caller]
fn field_display(self, key: impl Into<String>, value: impl Display) -> Result<T, Report<E>> {
self.report()
.map_err(|report| report.field_display(key, value))
}
#[track_caller]
fn field_debug(self, key: impl Into<String>, value: impl Debug) -> Result<T, Report<E>> {
self.report()
.map_err(|report| report.field_debug(key, value))
}
#[track_caller]
fn log_error(self) -> Option<T> {
self.report().log_error()
}
#[track_caller]
fn log_warning(self) -> Option<T> {
self.report().log_warning()
}
#[track_caller]
fn log_info(self) -> Option<T> {
self.report().log_info()
}
#[track_caller]
fn ignore(self) {
self.report().ignore();
}
#[track_caller]
fn assert_ok(self, invariant: impl IntoMessage) -> T {
self.report().assert_ok(invariant)
}
}
/// Marker error escalated into by [`ResultExt::assert_ok`], so the resulting panic
/// carries the assert call's own location and backtrace, with the original report kept
/// as its cause.
struct InvariantViolation;
impl Debug for InvariantViolation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InvariantViolation").finish()
}
}
impl Error for InvariantViolation {
fn message(&self) -> Option<&dyn Display> {
None
}
fn type_name(&self) -> &'static str {
"invariant"
}
}
impl<T, E: Error> ResultExt<T, E> for Result<T, Report<E>> {
fn report(self) -> Result<T, Report<E>> {
self
}
#[track_caller]
fn escalate<F: Error>(self, error: F) -> Result<T, Report<F>> {
match self {
Ok(value) => Ok(value),
Err(report) => Err(report.escalate(error)),
}
}
#[track_caller]
fn whatever<F: Whatever>(self, description: impl IntoMessage) -> Result<T, Report<F>> {
match self {
Ok(value) => Ok(value),
Err(report) => {
let new_error = F::from_error(report.error());
Err(report.escalate(new_error).message(description))
}
}
}
#[track_caller]
fn whatever_with<F, M>(self, description: impl FnOnce(&E) -> M) -> Result<T, Report<F>>
where
F: Whatever,
M: IntoMessage,
{
match self {
Ok(value) => Ok(value),
Err(report) => {
let description = description(report.error());
let new_error = F::from_error(report.error());
Err(report.escalate(new_error).message(description))
}
}
}
#[track_caller]
fn message(self, message: impl IntoMessage) -> Result<T, Report<E>> {
match self {
Ok(value) => Ok(value),
Err(report) => Err(report.message(message)),
}
}
#[track_caller]
fn suggestion(self, suggestion: impl IntoSuggestion) -> Result<T, Report<E>> {
match self {
Ok(value) => Ok(value),
Err(report) => Err(report.suggestion(suggestion)),
}
}
fn field(self, key: impl Into<String>, value: impl Into<Value>) -> Result<T, Report<E>> {
self.map_err(|report| report.field(key, value))
}
fn field_display(self, key: impl Into<String>, value: impl Display) -> Result<T, Report<E>> {
self.map_err(|report| report.field_display(key, value))
}
fn field_debug(self, key: impl Into<String>, value: impl Debug) -> Result<T, Report<E>> {
self.map_err(|report| report.field_debug(key, value))
}
fn log_error(self) -> Option<T> {
match self {
Ok(value) => Some(value),
Err(report) => {
tracing::error!(
error.r#type = report.error().type_name(),
error.code = report.error().code(),
"{report}"
);
None
}
}
}
fn log_warning(self) -> Option<T> {
match self {
Ok(value) => Some(value),
Err(report) => {
tracing::warn!(
error.r#type = report.error().type_name(),
error.code = report.error().code(),
"{report}"
);
None
}
}
}
fn log_info(self) -> Option<T> {
match self {
Ok(value) => Some(value),
Err(report) => {
tracing::info!(
error.r#type = report.error().type_name(),
error.code = report.error().code(),
"{report}"
);
None
}
}
}
fn ignore(self) {
let _ = self.log_error();
}
#[track_caller]
fn assert_ok(self, invariant: impl IntoMessage) -> T {
match self {
Ok(value) => value,
Err(report) => {
let message = invariant.into_message();
let escalated = report
.escalate(InvariantViolation)
.message(format!("violated invariant: {}", message.text));
let rendered =
crate::panic::decorate_with_pretty_panic_options(format!("{escalated:?}"));
crate::panic::panic_rendered(rendered)
}
}
}
}