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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! # Why did my program crash?
//! I wanted a simple answer and would love something similar to a stack trace.
//! I tried some popular crates and found that they are either too complex or too much work to use.
//! If the error is application-ending, I just want to pass it up the stack and eventually either print or serialize it.
//! And that's exactly what this library does, while remaining as small as possible.
//!
//! - 0 required dependencies (1 optional dependency for serialization or errors)
//! - 0 macros
//! - many optional features, so you only compile what you need
//!
//! It implements a single type [ErrorMessage] and a single trait [WithContext], which is implemented for [Result] and [Option].
//! It provides two functions:
//! - [with_err_context](WithContext::with_err_context) which takes anything that can be converted to [&str]
//! - [with_dyn_err_context](WithContext::with_dyn_err_context) which instead takes a closure that is only run in the error case
//!
//! No macros and no learning curve.
//! Wherever you use Rust's [?] operator, you now add `.with_err_context("Short description of what you are currently doing")?`.
//!
//! The output is neatly formatted, almost like a stacktrace.
//!
//!
//! # A simple example
//! ```rust,should_panic
//! # use std::fs::File;
//! # use std::io;
//! # use std::io::ErrorKind;
//! # struct Config;
//! use errors_with_context::prelude::*;
//! // OR just use WithContext
//! use errors_with_context::WithContext;
//!
//! fn read_file(path: &str) -> Result<File, io::Error> {
//! Err(io::Error::from(ErrorKind::UnexpectedEof))
//! }
//!
//! fn load_config() -> Result<Config, ErrorMessage> {
//! // [...]
//! let config_path = "config.json";
//! read_file(config_path)
//! .with_dyn_err_context(|| format!("Failed to read file '{}'", config_path))?;
//! // [...]
//! # Ok(Config)
//! }
//!
//! fn init_program() -> Result<(), ErrorMessage> {
//! load_config()
//! .with_err_context("Failed to load configuration")?;
//! // [...]
//! # Ok(())
//! }
//!
//! fn main() -> Result<(), ErrorMessage> {
//! init_program()
//! .with_err_context("Failed to start the program")?;
//! // [...]
//! # Ok(())
//! }
//! ```
//! prints
//! ```text
//! Failed to start the program
//! caused by: Failed to load configuration
//! caused by: Failed to read file 'config.json'
//! caused by: Kind(UnexpectedEof)
//! ```
//!
//! <br><br><br>
//!
//! # Using [ErrorMessages](ErrorMessage)
//!
//! You can use the functions [with_err_context](WithContext::with_err_context) and [with_dyn_err_context](WithContext::with_dyn_err_context) with [Results](Result) and [Options](Option).
//!
//! ## [.with_err_context()](WithContext::with_err_context)
//!
//! If your error messages are static strings, you can just include them like this:
//!
//! ```rust
//! # use std::io;
//! use errors_with_context::WithContext;
//! fn produce_none() -> Option<()> { None }
//! fn produce_err() -> Result<(), io::Error> { Err(io::ErrorKind::UnexpectedEof.into())}
//!
//! # let e =
//! produce_none()
//! .with_err_context("Something went wrong in function 'produce_none'");
//! # assert_eq!(e.unwrap_err().to_string(), "Something went wrong in function 'produce_none'");
//! ```
//! prints
//! ```text
//! Something went wrong in function 'produce_none'
//! ```
//!
//! ```rust
//! # use std::io;
//! # use errors_with_context::WithContext;
//! # fn produce_none() -> Option<()> { None }
//! # fn produce_err() -> Result<(), io::Error> { Err(io::ErrorKind::UnexpectedEof.into())}
//! #
//! # let e =
//! produce_err()
//! .with_err_context("Something went wrong in function 'produce_err'");
//! # assert_eq!(e.unwrap_err().to_string(), "Something went wrong in function 'produce_err'\n caused by: Kind(UnexpectedEof)");
//! ```
//! prints
//! ```text
//! Something went wrong in function 'produce_err'
//! caused by: Kind(UnexpectedEof)
//! ```
//!
//! ## [.with_dyn_err_context()](WithContext::with_dyn_err_context)
//!
//! ```rust
//! use errors_with_context::prelude::*;
//! # use std::io;
//! fn produce_none() -> Option<()> { None }
//! fn produce_err() -> Result<(), io::Error> { Err(io::ErrorKind::UnexpectedEof.into())}
//!
//! let variable = "Test";
//!
//! # let e =
//! produce_none()
//! .with_dyn_err_context(|| format!("Something went wrong in function 'produce_none'. Extra info: {variable}"));
//! # assert_eq!(e.unwrap_err().to_string(), "Something went wrong in function 'produce_none'. Extra info: Test");
//! ```
//! prints
//! ```text
//! Something went wrong in function 'produce_none'. Extra info: Test
//! ```
//!
//! ```rust
//! # use errors_with_context::prelude::*;
//! # use std::io;
//! # fn produce_none() -> Option<()> { None }
//! # fn produce_err() -> Result<(), io::Error> { Err(io::ErrorKind::UnexpectedEof.into())}
//! # let variable = "Test";
//! #
//! # let e =
//! produce_err()
//! .with_dyn_err_context(|| format!("Something went wrong in function 'produce_err'. Extra info: {variable}"));
//! # assert_eq!(e.unwrap_err().to_string(), "Something went wrong in function 'produce_err'. Extra info: Test\n caused by: Kind(UnexpectedEof)");
//! ```
//! prints
//! ```text
//! Something went wrong in function 'produce_err'. Extra info: Test
//! caused by: Kind(UnexpectedEof)
//! ```
//!
//! <br><br>
//!
//! # Creating an error message from scratch
//!
//! To get an [ErrorMessage] without an underlying [Error](std::error::Error)
//! ```rust
//! use errors_with_context::ErrorMessage;
//! ErrorMessage::new("Error description");
//! // prints "Error description" without listing a cause
//! ```
//!
//! Most of the time, you need a [Result<T, ErrorMessage>] instead.
//! [ErrorMessage::err] does exactly that, so you can immediately throw it with `?`:
//! ```rust
//! # use errors_with_context::ErrorMessage;
//! fn erroring_function() -> Result<String, ErrorMessage> {
//! ErrorMessage::err("Error description")?
//! // [...]
//! }
//! ```
//!
//! If you want to manually wrap an [Error](std::error::Error), there is the function [ErrorMessage::with_context].
//! Example:
//! ```rust
//! # use std::io;
//! # use errors_with_context::ErrorMessage;
//! ErrorMessage::with_context("Error description", io::Error::last_os_error());
//! ```
//!
//! <br><br>
//!
//! # A real-world example
//!
//! ```rust,should_panic
//! # use errors_with_context::{ErrorMessage, WithContext};
//! # use std::ffi::OsStr;
//! # use std::io::{Read, Error};
//! # use std::process::{Command, Stdio};
//! # struct Outputs{}
//! # fn parse_json(input: &str) -> Result<String, Error> {
//! # unimplemented!()
//! # }
//! fn main() -> Result<(), ErrorMessage> {
//! let outputs = get_outputs()
//! .with_err_context("Failed to get outputs")?;
//! # unimplemented!();
//! // [...]
//! }
//!
//! fn get_outputs() -> Result<Outputs, ErrorMessage> {
//! let cmd = "swaynsg"; // <-- misspelled "swaymsg" command will cause an error
//! let args = ["-t", "get_outputs"];
//! let process_output = run(cmd, &args)
//! .with_dyn_err_context(|| format!("Failed to run command '{cmd}' with args {args:?}"))?;
//! let outputs = parse_json(&process_output)
//! .with_err_context("Failed to parse swaymsg outputs JSON")?;
//! # unimplemented!()
//! // [...]
//! }
//!
//! fn run<I, S>(cmd: &str, args: I) -> Result<String, ErrorMessage>
//! where
//! I: IntoIterator<Item=S>,
//! S: AsRef<OsStr>,
//! {
//! let child = Command::new(cmd)
//! .args(args)
//! .stdin(Stdio::null())
//! .stdout(Stdio::piped())
//! .stderr(Stdio::piped())
//! .spawn()
//! .with_err_context("Failed to spawn process")?;
//! let mut stdout = child.stdout.with_err_context("Failed to get stdout from process")?;
//! let mut output = String::new();
//! stdout.read_to_string(&mut output).with_err_context("Failed to read stdout into buffer")?;
//! Ok(output)
//! }
//! ```
//! prints
//! ```text
//! Error: Failed to get outputs
//! caused by: Failed to run command 'swaynsg' with args ["-t", "get_outputs"]
//! caused by: Failed to spawn process
//! caused by: Os { code: 2, kind: NotFound, message: "No such file or directory" }
//! ```
//!
//! Much nicer to understand what the program was doing :)
//!
//! If you had just used the `?` operator everywhere, the error would have just said:
//! ```text
//! Os { code: 2, kind: NotFound, message: "No such file or directory" }
//! ```
//!
//! <br><br><br>
//!
//! # Features
//!
//! | Feature | Enabled by default | Dependencies | Effect |
//! |---------------------|--------------------|--------------------------------|------------------------------------------------------------|
//! | default | true | feature: "pretty_debug_errors" | Enable pretty debug errors |
//! | pretty_debug_errors | true | | Enable pretty debug errors |
//! | boolean_errors | false | | Allow turning booleans into [ErrorMessages](ErrorMessage) |
//! | serde | false | dependency: "serde" | Allow serialization of [ErrorMessages](ErrorMessage) |
//!
//! <br><br>
//!
//! ## Feature: `pretty_debug_errors`
//!
//! This feature is enabled by default and is responsible for the pretty error messages in the rest of this page.
//! If the feature is disabled, the more ideomatic rust debug error formatting is used:
//! ```text
//! Error: ErrorMessage { message: "Failed to get outputs", cause: ErrorMessage { message: "Failed to run command 'swaynsg' with args [\"-t\", \"get_outputs\"]", cause: ErrorMessage { message: "Failed to spawn process", cause: Some(Os { code: 2, kind: NotFound, message: "No such file or directory" }) } } }
//! ```
//!
//! Formatted by hand, it looks like this:
//! ```text
//! Error: ErrorMessage {
//! message: "Failed to get outputs",
//! cause: ErrorMessage {
//! message: "Failed to run command 'swaynsg' with args [\"-t\", \"get_outputs\"]",
//! cause: ErrorMessage {
//! message: "Failed to spawn process",
//! cause: Some(
//! Os {
//! code: 2,
//! kind: NotFound,
//! message: "No such file or directory"
//! }
//! )
//! }
//! }
//! }
//! ```
//!
//! Still readable, but not as nice for humans.
//!
//! <br>
//!
//! ## Feature: `boolean_errors`
//!
//! (disabled by default)
//!
//! This adds the trait [BooleanErrors] and with it 4 functions to the [bool] type:
//! - [error_if_true](BooleanErrors::error_if_true)
//! - [error_if_false](BooleanErrors::error_if_false)
//! - [error_dyn_if_true](BooleanErrors::error_dyn_if_true)
//! - [error_dyn_if_false](BooleanErrors::error_dyn_if_false)
//!
//! This allows for cool code like this:
//! ```rust
//! # use std::path::Path;
//! use errors_with_context::{BooleanErrors, ErrorMessage};
//! # fn func() -> Result<(), ErrorMessage> {
//! let path = Path::new("test.file");
//! path.exists()
//! .error_if_false("Expected file to exist!")?;
//! # Ok(())
//! # }
//! # fn main() {
//! # let string = func().unwrap_err().to_string();
//! # assert_eq!(string, "Expected file to exist!");
//! # }
//! ```
//! or with more dynamic context:
//! ```rust
//! # use std::path::Path;
//! use errors_with_context::prelude::*;
//! # fn func() -> Result<(), ErrorMessage> {
//! let path = Path::new("test.file");
//! path.exists()
//! .error_dyn_if_false(|| format!("Expected file '{}' to exist!", path.display()))?;
//! # Ok(())
//! # }
//! # fn main() {
//! # let string = func().unwrap_err().to_string();
//! # assert_eq!(string, "Expected file 'test.file' to exist!");
//! # }
//! ```
//!
//! Very useful, when doing lots of checks that aren't immediately errors.
//!
//! <br>
//!
//!
//! ## Feature: `send`
//!
//! (disabled by default)
//!
//! This adds the requirements for all causes to be [Send].
//! This is useful for sending errors between threads.
//!
//! Example:
//! ```rust
//! # mod tokio {
//! # use std::thread::JoinHandle;
//! # use errors_with_context::ErrorMessage;
//! # pub async fn spawn(future: impl Future) -> Result<Result<bool, ErrorMessage>, ErrorMessage> {
//! # ErrorMessage::err("mocked function")
//! # }
//! # }
//! # async fn ping(){}
//! # use errors_with_context::{ErrorMessage, WithContext};
//! # async fn func() -> Result<(), ErrorMessage>{
//! let host_reachable = tokio::spawn(ping()).await
//! .with_err_context("Failed to ping host")??;
//! # Ok(())
//! # }
//! ```
//!
//! <br>
//!
//!
//! ## Feature: `serde`
//!
//! (disabled by default)
//!
//! This feature enables serialization of [ErrorMessage]s with [serde](https://crates.io/crates/serde).
//!
//! ```
//! # use std::convert::Infallible;
//! # use std::io;
//! # use errors_with_context::prelude::*;
//! #
//! let result: Result<Infallible, _> = Err(io::Error::from(io::ErrorKind::NotFound))
//! .with_err_context("Failed to read file")
//! .with_err_context("Failed to load configuration")
//! .with_err_context("Failed to start the program");
//! let message = result.unwrap_err();
//! let json = serde_json::to_string_pretty(&message).unwrap();
//! #
//! # assert_eq!(json, r#"{
//! # "message": "Failed to start the program",
//! # "cause": {
//! # "message": "Failed to load configuration",
//! # "cause": {
//! # "message": "Failed to read file",
//! # "cause": {
//! # "message": "entity not found",
//! # "cause": null
//! # }
//! # }
//! # }
//! # }"#)
//! ```
//! results in
//! ```json
//! {
//! "message": "Failed to start the program",
//! "cause": {
//! "message": "Failed to load configuration",
//! "cause": {
//! "message": "Failed to read file",
//! "cause": {
//! "message": "entity not found",
//! "cause": null
//! }
//! }
//! }
//! }
//! ```
pub use crateErrorMessage;
/// Group all traits of this crate
/// [WithContext] is implemented for [Result] and [Option]
/// see [with_err_context](WithContext::with_err_context) and [with_dyn_err_context](WithContext::with_dyn_err_context) for more details
pub use BooleanErrors;