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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! A string-based error type.
//!
//! # Introduction
//!
//! This crate provides a string-based error type, `StrError`, that
//! implements `std::error::Error`. `StrError`s behave much like
//! `String`s, except they may contain another error boxed inside
//! them, known as the "source" or "cause". Since the source can have
//! a source itself, sources form chains of errors, each error adding
//! context to the preceeding one.
//!
//! When a `StrError` is returned from `main`, its `Debug`
//! implementation causes the output of a CLI application to look like
//! this
//!
//! ```text
//! Error: ...
//! Caused by: ...
//! Caused by: ...
//! ...
//! ```
//!
//! Each "Caused by:" line corresponds to a boxed error in the chain
//! of sources.
//!
//! # The prelude
//!
//! This crate has a prelude to bring in all the things you need at
//! once.
//!
//! ```
//! use strerror::prelude::*;
//! ```
//!
//! Because some of the crate's functionality is contained in
//! extension traits, this is quite useful. The examples below all
//! assume the prelude is used.
//!
//! # Creating `StrError`s
//!
//! As with `String`s, there are quite a few ways to create a
//! `StrError`. Some have a `String` equivalent so we present these
//! alongside each other.
//!
//! ```
//! # use strerror::prelude::*;
//! // String                             // StrError
//! let str1 = "Error!".to_string();      let err1 = "Error!".to_error();
//! let str2 = String::from("Error!");    let err2 = StrError::from("Error!");
//! let str3: String = "Error!".into();   let err3: StrError = "Error!".into();
//! let str4 = format!("Error! #{}", 1);  let err4 = eformat!("Error! #{}", 1);
//! ```
//!
//! The above lines all create `StrError`s without a "source" or
//! "cause". Next we show two equivalent ways to create a `StrError`
//! containing a source. The `StrError` takes ownership of the source
//! which may or may not be another `StrError`.
//!
//! ```
//! # use strerror::prelude::*;
//! use std::io::Error as IoError;
//!
//! let source1 = IoError::from_raw_os_error(5);
//! let err1 = StrError::from_error(source1, "I/O error occurred");
//!
//! let source2 = IoError::from_raw_os_error(5);
//! let err2 = source2.chain("I/O error occurred");
//! ```
//!
//! The advantage of the second way using the `chain` method comes
//! from the fact that, in chaining methods together, an error chain
//! itself can be created.
//!
//! ```
//! # use strerror::prelude::*;
//! fn main() -> Result<(), StrError> {
//! # || -> Result<(), StrError> {
//!     let err = "Base error".to_error()
//!         .chain("Higher level error")
//!         .chain("Application error");
//!     Err(err)
//! # }().unwrap_err(); Ok(())
//! }
//! ```
//!
//! gives output
//!
//! ```text
//! Error: Application error
//! Caused by: Higher level error
//! Caused by: Base error
//! ```
//!
//! # Returning `Result`s
//!
//! While the `chain` method adds context to error types directly, we
//! can do a similar thing with the `Err` values contained within
//! `Result`s, with the `chain_err` method.
//!
//! ```
//! # use strerror::prelude::*;
//! use std::fs::File;
//!
//! fn main() -> Result<(), StrError> {
//! # || -> Result<(), StrError> {
//!     let file = "missing-file";
//!     let _ = File::open(file)                             // a Result
//!         .chain_err(format!("Failed to open {}", file))?; // main exits here
//!     Ok(())
//! # }().unwrap_err(); Ok(())
//! }
//! ```
//!
//! gives output
//!
//! ```text
//! Error: Failed to open missing-file
//! Caused by: No such file or directory (os error 2)
//! ```
//!
//! The `Result` is converted to the correct type by `chain_err` and
//! context is applied to the boxed error.
//!
//! # Converting `Option`s
//!
//! Sometimes `None` represents an application error and it is
//! desirable to convert an `Option<T>` into a
//! `Result<T, StrError>`. There is no special method needed in this
//! case and you can use `ok_or`/`ok_or_else` with a new `StrError`
//! (created using `to_error`, for example).
//!
//! ```
//! # use strerror::prelude::*;
//! use std::env;
//!
//! fn main() -> Result<(), StrError> {
//! # || -> Result<(), StrError> {
//!     let _ = env::var_os("MISSING_VAR")                       // an Option
//!         .ok_or_else(|| "MISSING_VAR not found".to_error())?; // main exits here
//!     Ok(())
//! # }().unwrap_err(); Ok(())
//! }
//! ```
//!
//! gives output
//!
//! ```text
//! Error: MISSING_VAR not found
//! ```
//!
//! However, if your containing function returns a
//! `Result<T, StrError>`, it is sufficient to pass just a `&str` or
//! `String` to `ok_or`/`ok_or_else`. This produces a
//! `Result<T, &str>` or `Result<T, String>`, but when used with the
//! `?` operator it is converted to a `Result<T, StrError>`. This
//! works because `StrError` implements `From<&str>` and
//! `From<String>`.
//!
//! ```
//! # use strerror::prelude::*;
//! use std::env;
//!
//! fn main() -> Result<(), StrError> {
//! # || -> Result<(), StrError> {
//!     let _ = env::var_os("MISSING_VAR")
//!         .ok_or("MISSING_VAR not found")?;
//!     Ok(())
//! # }().unwrap_err(); Ok(())
//! }
//! ```
//!
//! # `From` conversions
//!
//! `From` conversions are implemented for most of the standard
//! library error types, so you can return a `Result` containing one
//! directly from a function returning a `Result<T, StrError>`, using
//! the `?` operator.
//!
//! ```
//! # use strerror::prelude::*;
//! use std::fs::File;
//!
//! fn main() -> Result<(), StrError> {
//! # || -> Result<(), StrError> {
//!     let file = "missing-file";
//!     let _ = File::open(file)?; // main exits here
//!     Ok(())
//! # }().unwrap_err(); Ok(())
//! }
//! ```
//!
//! gives output
//!
//! ```text
//! Error: std::io::Error
//! Caused by: No such file or directory (os error 2)
//! ```
//!
//! `From` conversions are also implemented for `&str` and `String`,
//! as discussed above.
//!
//! However, for other error types, if you wish to use the `?`
//! operator, you will first need to call the `chain_err` method to
//! convert the `Result` into a `Result<T, StrError>`. Of course you
//! may choose to return a `Result<T, Box<dyn std::error::Error>>`
//! from your function instead, for which `?` will work for all error
//! types.
//!
//! # `Deref`
//!
//! `StrError`s deref to a `String`, so you can use many of the usual
//! `String` methods.
//!
//! ```
//! # use strerror::prelude::*;
//! fn main() -> Result<(), StrError> {
//! # || -> Result<(), StrError> {
//!     let mut err = "This is".to_error();
//!     *err += " an error";
//!     err.push_str(" message");
//!     Err(err)
//! # }().unwrap_err(); Ok(())
//! }
//! ```
//!
//! gives output
//!
//! ```text
//! Error: This is an error message
//! ```
//!
//! # Iterating through the source chain
//!
//! A reference to a `StrError` can be iterated over to examine its
//! chain of boxed sources.
//!
//! ```
//! # use strerror::prelude::*;
//! use std::io::Error as IoError;
//!
//! fn main() -> Result<(), StrError> {
//!     let err = IoError::from_raw_os_error(5)
//!         .chain("Failure reading disk")
//!         .chain("Application error");
//!     for e in &err {
//!         println!(
//!             "Error: {:31} Is StrError?: {}",
//!             e,
//!             e.downcast_ref::<StrError>().is_some()
//!         );
//!     }
//!     Ok(())
//! }
//! ```
//!
//! gives output
//!
//! ```text
//! Error: Application error               Is StrError?: true
//! Error: Failure reading disk            Is StrError?: true
//! Error: Input/output error (os error 5) Is StrError?: false
//! ```

use std::borrow::Cow;
use std::error::Error;
use std::fmt::Error as FmtError;
use std::fmt::{Debug, Display, Formatter};
use std::ops::{Deref, DerefMut};

/// Reexports of `eformat`, `ErrorChainExt`, `ResultChainErrExt`,
/// `StrError` and `StringToErrorExt`.
pub mod prelude {
    pub use super::{
        eformat, ErrorChainExt, ResultChainErrExt, StrError, StringToErrorExt,
    };
}

/// A string-based error type implementing `std::error::Error`.
///
/// `From` conversions to `StrError` are implemented for most standard
/// library error types, and for `String`s and `&str`s. `Deref`
/// converts to a `String`.
///
/// See crate level documentation for usage examples.
pub struct StrError {
    description: String,
    source: Option<Box<dyn Error + Send + Sync>>,
}

impl StrError {
    /// Convert an error of any type to a `StrError`, adding context
    /// and boxing it.
    pub fn from_error<T, E>(err: E, context: T) -> Self
    where
        T: Into<String>,
        E: Into<Box<dyn Error + Send + Sync>>,
    {
        StrError { description: context.into(), source: Some(err.into()) }
    }

    /// Create an iterator over a `StrError` and it's sources. When
    /// using the iterator, the first item retrieved is a reference to
    /// the `StrError` itself (as a trait object). This is then
    /// followed by the chain of sources. You can also use
    /// `&StrError`'s implementation of `IntoIterator` to obtain an
    /// iterator.
    pub fn iter(&self) -> Iter<'_> {
        Iter { next: Some(self) }
    }
}

impl Error for StrError {
    /// Return the lower-level source of this `StrError`, if any.
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.as_ref().map(|e| &**e as &(dyn Error + 'static))
    }
}

impl Display for StrError {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
        Display::fmt(&**self, f)
    }
}

impl Debug for StrError {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
        write!(f, "{}", self)?;
        for e in self.iter().skip(1) {
            write!(f, "\nCaused by: {}", e)?;
        }
        Ok(())
    }
}

/// An iterator producing a reference to a `StrError` (as a trait
/// object), followed by its chain of sources.
pub struct Iter<'a> {
    next: Option<&'a (dyn Error + 'static)>,
}

impl<'a> Iterator for Iter<'a> {
    type Item = &'a (dyn Error + 'static);

    fn next(&mut self) -> Option<Self::Item> {
        match &self.next {
            None => None,
            Some(e) => {
                let next = self.next;
                self.next = e.source();
                next
            }
        }
    }
}

impl<'a> IntoIterator for &'a StrError {
    type Item = &'a (dyn Error + 'static);
    type IntoIter = Iter<'a>;
    fn into_iter(self) -> Iter<'a> {
        self.iter()
    }
}

/// Trait providing `chain` for converting an error of any type to a
/// `StrError`.
///
/// See crate level documentation for usage examples.
pub trait ErrorChainExt<T> {
    /// Convert an error of any type to a `StrError`, adding context.
    fn chain(self, context: T) -> StrError;
}

impl<T, E> ErrorChainExt<T> for E
where
    T: Into<String>,
    E: Into<Box<dyn Error + Send + Sync>>,
{
    fn chain(self, context: T) -> StrError {
        StrError::from_error(self.into(), context.into())
    }
}

/// Trait providing `chain_err` for mapping the `Err` value within a
/// `Result` to a `StrError`.
///
/// See crate level documentation for usage examples.
pub trait ResultChainErrExt<T, U> {
    /// Map the `Err` value within a `Result` to a `StrError`, adding
    /// context.
    fn chain_err(self, context: T) -> Result<U, StrError>;
}

impl<T, U, E> ResultChainErrExt<T, U> for Result<U, E>
where
    T: Into<String>,
    E: Into<Box<dyn Error + Send + Sync>>,
{
    fn chain_err(self, context: T) -> Result<U, StrError> {
        self.map_err(|e| StrError::from_error(e.into(), context.into()))
    }
}

/// Trait providing `to_error` for converting a `String` or `&str` to
/// a `StrError`.
///
/// See crate level documentation for usage examples.
pub trait StringToErrorExt {
    /// Convert a `String` or `&str` to a `StrError`.
    fn to_error(self) -> StrError;
}

impl<T> StringToErrorExt for T
where
    T: Into<String>,
{
    fn to_error(self) -> StrError {
        StrError::from(self.into())
    }
}

/// A macro for creating a `StrError` using interpolation of runtime
/// expressions (like `format!`).
///
/// `eformat!` is an extremely simple macro meant to save some
/// keystrokes when creating `StrError`s. The name was chosen to
/// mirror that of `eprint!` in the standard library, which is an
/// "error" version of `print!`.
///
/// Call `eformat!` as you would call `format!`, but you will get a
/// `StrError` instead of a `String`.
#[macro_export]
macro_rules! eformat {
    ($($arg:tt)*) => {
        StrError::from(format!($($arg)*))
    }
}

// Deref conversion for StrError.
impl Deref for StrError {
    type Target = String;

    fn deref(&self) -> &String {
        &self.description
    }
}
impl DerefMut for StrError {
    fn deref_mut(&mut self) -> &mut String {
        &mut self.description
    }
}

// From conversions for Strings,  &strs etc
impl From<Box<str>> for StrError {
    fn from(s: Box<str>) -> Self {
        StrError { description: s.into_string(), source: None }
    }
}
impl<'a> From<Cow<'a, str>> for StrError {
    fn from(s: Cow<'a, str>) -> Self {
        StrError { description: s.into_owned(), source: None }
    }
}
impl From<&str> for StrError {
    fn from(s: &str) -> Self {
        StrError { description: s.to_owned(), source: None }
    }
}
impl From<String> for StrError {
    fn from(s: String) -> Self {
        StrError { description: s, source: None }
    }
}
impl From<&String> for StrError {
    fn from(s: &String) -> Self {
        StrError { description: s.clone(), source: None }
    }
}

// From conversions for stdlib errors.
macro_rules! impl_from {
    ($from:ty) => {
        impl From<$from> for StrError {
            fn from(err: $from) -> Self {
                StrError::from_error(err, stringify!($from))
            }
        }
    };
    ($from:ty, $param:ident $(, $bound:ident)* ) => {
        impl<$param> From<$from> for StrError
        where
            $param: Send + Sync + 'static $(+ $bound)*,
        {
            fn from(err: $from) -> Self {
                StrError::from_error(err, stringify!($from))
            }
        }
    };
}

impl_from!(std::alloc::LayoutErr);
impl_from!(std::array::TryFromSliceError);
impl_from!(std::boxed::Box<T>, T, Error);
impl_from!(std::cell::BorrowError);
impl_from!(std::cell::BorrowMutError);
impl_from!(std::char::CharTryFromError);
impl_from!(std::char::DecodeUtf16Error);
impl_from!(std::char::ParseCharError);
impl_from!(std::env::JoinPathsError);
impl_from!(std::env::VarError);
impl_from!(std::ffi::FromBytesWithNulError);
impl_from!(std::ffi::IntoStringError);
impl_from!(std::ffi::NulError);
impl_from!(std::fmt::Error);
impl_from!(std::io::Error);
impl_from!(std::io::IntoInnerError<T>, T, Debug);
impl_from!(std::net::AddrParseError);
impl_from!(std::num::ParseFloatError);
impl_from!(std::num::ParseIntError);
impl_from!(std::num::TryFromIntError);
impl_from!(std::path::StripPrefixError);
impl_from!(std::str::ParseBoolError);
impl_from!(std::str::Utf8Error);
impl_from!(std::string::FromUtf16Error);
impl_from!(std::string::FromUtf8Error);
impl_from!(std::string::ParseError);
impl_from!(std::sync::PoisonError<T>, T);
impl_from!(std::sync::TryLockError<T>, T);
impl_from!(std::sync::mpsc::RecvError);
impl_from!(std::sync::mpsc::RecvTimeoutError);
impl_from!(std::sync::mpsc::SendError<T>, T);
impl_from!(std::sync::mpsc::TryRecvError);
impl_from!(std::sync::mpsc::TrySendError<T>, T);
impl_from!(std::time::SystemTimeError);