explicit-error 0.2.3

Explicit concrete Error type for binary crates
Documentation
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
use crate::domain::Domain;
use crate::fault::*;
use crate::unwrap_failed;
use std::{error::Error as StdError, fmt::Display};

/// Use `Result<T, explicit_error::Error>` as the return type of any binary crate
/// faillible function returning errors.
/// The [Error::Fault] variant is for errors that should not happen but cannot panic.
/// The [Error::Domain] variant is for domain errors that provide feedbacks to the user.
/// For library or functions that require the caller to pattern match on the returned error, a dedicated type is prefered.
#[derive(Debug)]
pub enum Error<D> {
    Domain(Box<D>), // Box for size: https://doc.rust-lang.org/clippy/lint_configuration.html#large-error-threshold
    Fault(Fault),
}

impl<D> StdError for Error<D>
where
    D: StdError + 'static,
{
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Error::Domain(explicit_error) => {
                explicit_error.source().or(Some(explicit_error.as_ref()))
            }
            Error::Fault(fault) => fault.source().or(Some(fault)),
        }
    }
}

impl<D> Display for Error<D>
where
    D: StdError,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Domain(explicit_error) => Display::fmt(&explicit_error, f),
            Error::Fault(fault) => fault.fmt(f),
        }
    }
}

impl<D> Error<D>
where
    D: StdError + 'static,
{
    /// Return true if it's a [Error::Domain] variant
    pub fn is_domain(&self) -> bool {
        matches!(*self, Error::Domain(_))
    }

    /// Return true if it's a [Error::Fault] variant
    pub fn is_fault(&self) -> bool {
        !self.is_domain()
    }

    /// Unwrap the [Error::Domain] variant, panic otherwise
    pub fn unwrap(self) -> D {
        match self {
            Self::Domain(e) => *e,
            Self::Fault(f) => unwrap_failed("called `Error::unwrap()` on an `Fault` value", &f),
        }
    }

    /// Unwrap the [Error::Fault] variant, panic otherwise
    pub fn unwrap_fault(self) -> Fault {
        match self {
            Self::Fault(b) => b,
            Self::Domain(e) => {
                unwrap_failed("called `Error::unwrap_err()` on an `Domain` value", &e)
            }
        }
    }

    /// Try to downcast the source of the type wrapped in either [Error::Domain] or [Error::Fault] variant.
    /// If it is not set try to downcast the type wrapped.
    /// Usefull to assert_eq! in tests
    /// # Examples
    /// ```rust
    /// use explicit_error_exit::{ExitError, derive::ExitError, Error};
    /// # use std::process::ExitCode;
    /// #[test]
    /// fn test() {
    ///     assert_eq!(to_test().unwrap_err().downcast_source_ref()::<MyError>().unwrap(), &MyError::Foo);
    /// }
    ///
    /// #[derive(ExitError, Debug)]
    /// enum MyError {
    ///     Foo,
    /// }
    ///
    /// # impl From<&MyError> for ExitError {
    /// #     fn from(value: &MyError) -> Self {
    /// #         match value {
    /// #             MyError::Foo => ExitError::new(
    /// #                     "Something went wrong because ..",
    /// #                     ExitCode::from(42)
    /// #                 ),
    /// #         }
    /// #     }
    /// # }
    ///
    /// fn to_test() -> Result<(), Error> {
    ///     Err(MyError::Foo)?;
    ///     Ok(())
    /// }
    /// ```
    pub fn downcast_source_ref<E>(&self) -> Option<&E>
    where
        E: StdError + 'static,
    {
        match self {
            Error::Domain(domain) => match domain.source() {
                Some(_) => domain.source().unwrap(),
                None => domain as &dyn StdError,
            },
            Error::Fault(fault) => match fault.source() {
                Some(_) => fault.source().unwrap(),
                None => fault as &dyn StdError,
            },
        }
        .downcast_ref::<E>()
    }
}

impl<D> Error<D>
where
    D: Domain,
{
    /// Try to downcast the source of the type wrapped in either [Error::Domain] or [Error::Fault] variant.
    /// If it is not set try to downcast the type wrapped.
    /// Usefull to assert_eq! in tests
    /// # Examples
    /// ```rust
    /// use explicit_error_exit::{ExitError, derive::ExitError, Error};
    /// # use std::process::ExitCode;
    /// #[test]
    /// fn test() {
    ///     assert_eq!(to_test().unwrap_err().downcast_source::<MyError>().unwrap(), MyError::Foo);
    /// }
    ///
    /// #[derive(ExitError, Debug)]
    /// enum MyError {
    ///     Foo,
    /// }
    ///
    /// # impl From<&MyError> for ExitError {
    /// #     fn from(value: &MyError) -> Self {
    /// #         match value {
    /// #             MyError::Foo => ExitError::new(
    /// #                     "Something went wrong because ..",
    /// #                     ExitCode::from(42)
    /// #                 ),
    /// #         }
    /// #     }
    /// # }
    ///
    /// fn to_test() -> Result<(), Error> {
    ///     Err(MyError::Foo)?;
    ///     Ok(())
    /// }
    /// ```
    pub fn downcast_source<E>(self) -> Result<E, Box<dyn std::error::Error + 'static + Send + Sync>>
    where
        E: StdError + 'static,
    {
        match self {
            Error::Domain(domain) => match domain.source() {
                Some(_) => domain.into_source().unwrap(),
                None => domain,
            },
            Error::Fault(fault) => match fault.source() {
                Some(_) => fault.source.unwrap(),
                None => Box::new(fault),
            },
        }
        .downcast::<E>()
        .map(|o| *o)
    }

    /// Add context of either [Error::Domain] or [Error::Fault] variant.
    /// Override existing context
    pub fn with_context(self, context: impl Display) -> Self {
        match self {
            Error::Domain(d) => Error::Domain(Box::new(d.with_context(context))),
            Error::Fault(fault) => Error::Fault(fault.with_context(context)),
        }
    }

    /// Return the context of either [Error::Domain] or [Error::Fault] variant.
    pub fn context(&self) -> Option<&str> {
        match self {
            Error::Domain(d) => d.context(),
            Error::Fault(fault) => fault.context(),
        }
    }
}

pub fn errors_chain_debug(source: &dyn StdError) -> String {
    use std::fmt::Write;
    let mut source = source;
    let mut str = format!("{:?}", source);

    while source.source().is_some() {
        source = source.source().unwrap();
        let _ = write!(&mut str, "->{:?}", source);
    }

    str
}

/// To use this trait on [Result] import the prelude `use explicit_error::prelude::*`
pub trait ResultFault<T, S> {
    /// Convert with a closure any error wrapped in a [Result] to an [Error]. Returning an [Ok] convert the wrapped type to
    /// [Error::Domain].
    /// Returning an [Err] generates a [Fault] with the orginal error has its source.
    /// # Examples
    /// Pattern match to convert to an [Error::Domain]
    /// ```rust
    /// # use http::StatusCode;
    /// # use problem_details::ProblemDetails;
    /// # use http::Uri;
    /// # use explicit_error_http::{Error, prelude::*, HttpError, derive::HttpError};
    /// fn authz_middleware(public_identifier: &str) -> Result<(), Error> {
    ///     let entity = fetch_bar(&public_identifier).map_err_or_fault(|e|
    ///         match e {
    ///             sqlx::Error::RowNotFound => Ok(
    ///                 NotFoundError::Bar(
    ///                     public_identifier.to_string())),
    ///             _ => Err(e), // Convert to Error::Fault
    ///         }
    ///     )?;
    ///
    ///     Ok(entity)
    /// }
    /// # fn fetch_bar(public_identifier: &str) -> Result<(), sqlx::Error> {
    /// #    Err(sqlx::Error::RowNotFound)
    /// # }
    /// # #[derive(HttpError, Debug)]
    /// # enum NotFoundError {
    /// #     Bar(String)
    /// # }
    /// # impl From<&NotFoundError> for HttpError {
    /// #   fn from(value: &NotFoundError) -> Self {
    /// #       let (label, id) = match value {
    /// #           NotFoundError::Bar(public_identifier) => ("Bar", public_identifier)
    /// #       };
    /// #       HttpError::new(
    /// #           StatusCode::NOT_FOUND,
    /// #           ProblemDetails::new()
    /// #               .with_type(Uri::from_static("/errors/not-found"))
    /// #               .with_title("Not found")
    /// #               .with_detail(format!("Unknown {label} with identifier {id}."))
    /// #       )
    /// #   }
    /// # }
    /// ```
    fn map_err_or_fault<F, E, D>(self, op: F) -> Result<T, Error<D>>
    where
        F: FnOnce(S) -> Result<E, S>,
        E: Into<Error<D>>,
        S: StdError + 'static + Send + Sync,
        D: Into<Error<D>>;

    /// Convert any [Result::Err] into a [Result::Err] wrapping a [Fault]
    /// Use [fault](ResultFault::or_fault) instead if the error implements [std::error::Error]
    ///  ```rust
    /// # use std::fs::File;
    /// # use explicit_error_exit::{Error, prelude::*};
    /// fn foo() -> Result<(), Error> {
    ///     let file: Result<File, std::io::Error> = File::open("foo.conf");
    ///     file.or_fault_no_source().with_context("Configuration file foo.conf is missing.")?;
    ///
    ///     Err("error message").or_fault_no_source()?;
    ///     # Ok(())
    /// }
    /// ```
    fn or_fault_no_source(self) -> Result<T, Fault>;

    /// Convert any [Result::Err] wrapping an error that implements
    /// [std::error::Error] into a [Result::Err] wrapping a [Fault]
    ///  ```rust
    /// # use std::fs::File;
    /// # use explicit_error_exit::{Error, prelude::*};
    /// fn foo() -> Result<(), Error> {
    ///     Err(sqlx::Error::RowNotFound)
    ///         .or_fault()
    ///         .with_context("Configuration file foo.conf is missing.")?;
    ///     # Ok(())
    /// }
    /// ```
    fn or_fault(self) -> Result<T, Fault>
    where
        S: StdError + 'static + Send + Sync;

    /// Convert any [Result::Err] into a [Result::Err] wrapping a [Fault] forcing backtrace capture
    /// Use [or_fault_force](ResultFault::or_fault_force) instead if the error implements [std::error::Error]
    ///  ```rust
    /// # use std::fs::File;
    /// # use explicit_error_exit::{Error, prelude::*};
    /// fn foo() -> Result<(), Error> {
    ///     let file: Result<File, std::io::Error> = File::open("foo.conf");
    ///     file.or_fault_force().with_context("Configuration file foo.conf is missing.")?;
    ///     # Ok(())
    /// }
    /// ```
    fn or_fault_no_source_force(self) -> Result<T, Fault>;

    /// Convert any [Result::Err] wrapping an error that implements
    /// [std::error::Error] into a [Result::Err] wrapping a [Fault] forcing backtrace capture
    ///  ```rust
    /// # use std::fs::File;
    /// # use explicit_error_exit::{Error, prelude::*};
    /// fn foo() -> Result<(), Error> {
    ///     Err(sqlx::Error::RowNotFound)
    ///         .or_fault_force()
    ///         .with_context("Configuration file foo.conf is missing.")?;
    ///     # Ok(())
    /// }
    /// ```
    fn or_fault_force(self) -> Result<T, Fault>
    where
        S: StdError + 'static + Send + Sync;
}

impl<T, S> ResultFault<T, S> for Result<T, S> {
    fn map_err_or_fault<F, E, D>(self, op: F) -> Result<T, Error<D>>
    where
        F: FnOnce(S) -> Result<E, S>,
        E: Into<Error<D>>,
        S: StdError + 'static + Send + Sync,
        D: Into<Error<D>>,
    {
        match self {
            Ok(ok) => Ok(ok),
            Err(error) => Err(match op(error) {
                Ok(d) => d.into(),
                Err(e) => Fault::new().with_source(e).into(),
            }),
        }
    }

    fn or_fault_no_source(self) -> Result<T, Fault> {
        match self {
            Ok(ok) => Ok(ok),
            Err(_) => Err(Fault::new()),
        }
    }

    fn or_fault_no_source_force(self) -> Result<T, Fault> {
        match self {
            Ok(ok) => Ok(ok),
            Err(_) => Err(Fault::new_force()),
        }
    }

    fn or_fault(self) -> Result<T, Fault>
    where
        S: StdError + 'static + Send + Sync,
    {
        match self {
            Ok(ok) => Ok(ok),
            Err(error) => Err(Fault::new().with_source(error)),
        }
    }

    fn or_fault_force(self) -> Result<T, Fault>
    where
        S: StdError + 'static + Send + Sync,
    {
        match self {
            Ok(ok) => Ok(ok),
            Err(error) => Err(Fault::new_force().with_source(error)),
        }
    }
}

/// To use this trait on [Result] import the prelude `use explicit_error::prelude::*`
pub trait ResultError<T, D>
where
    D: Domain,
{
    /// Pattern match on the [Error] source from either the [Error::Fault] or [Error::Domain] variant
    /// if its type is the closure's parameter type.
    /// # Examples
    /// ```rust
    /// # use http::StatusCode;
    /// # use http::Uri;
    /// # use problem_details::ProblemDetails;
    /// # use explicit_error_http::{prelude::*, HttpError, Result, derive::HttpError};
    /// # #[derive(HttpError, Debug)]
    /// # enum MyError {
    /// #     Foo,
    /// #     Bar,
    /// # }
    /// # impl From<&MyError> for HttpError {
    /// #    fn from(value: &MyError) -> Self {
    /// #        match value {
    /// #            MyError::Foo | MyError::Bar => HttpError::new(
    /// #                    StatusCode::BAD_REQUEST,
    /// #                    ProblemDetails::new()
    /// #                        .with_type(Uri::from_static("/errors/my-domain/foo"))
    /// #                        .with_title("Foo format incorrect.")
    /// #                ),
    /// #        }
    /// #    }
    /// # }
    /// # fn handler() -> Result<()> {
    ///     let err: Result<()> = Err(MyError::Foo)?;
    ///     
    ///     // Do the map if the source's type of the Error is MyError
    ///     err.try_map_on_source(|e| {
    ///         match e {
    ///             MyError::Foo => HttpError::new(
    ///                 StatusCode::FORBIDDEN,
    ///                 ProblemDetails::new()
    ///                     .with_type(Uri::from_static("/errors/forbidden"))
    ///                ),
    ///             MyError::Bar => HttpError::new(
    ///                 StatusCode::UNAUTHORIZED,
    ///                 ProblemDetails::new()
    ///                     .with_type(Uri::from_static("/errors/unauthorized"))
    ///                ),
    ///         }
    ///     })?;
    /// #     Ok(())
    /// # }
    /// ```
    fn try_map_on_source<F, S, E>(self, op: F) -> Result<T, Error<D>>
    where
        F: FnOnce(S) -> E,
        S: StdError + 'static,
        E: Into<Error<D>>;

    /// Add a context to any variant of an [Error] wrapped in a [Result::Err]
    /// # Examples
    /// ```rust
    /// use explicit_error::{prelude::*, Fault};
    /// Err::<(), _>(Fault::new()).with_context("Foo bar");
    /// ```
    fn with_context(self, context: impl Display) -> Result<T, Error<D>>;
}

impl<T, D> ResultError<T, D> for Result<T, Error<D>>
where
    D: Domain,
    T: std::fmt::Debug,
{
    fn try_map_on_source<F, S, E>(self, op: F) -> Result<T, Error<D>>
    where
        F: FnOnce(S) -> E,
        S: StdError + 'static,
        E: Into<Error<D>>,
    {
        match self {
            Ok(ok) => Ok(ok),
            Err(error) => match error {
                Error::Domain(d) => {
                    if d.source().is_some() && (d.source().as_ref().unwrap()).is::<S>() {
                        return Err(op(*d.into_source().unwrap().downcast::<S>().unwrap()).into());
                    }

                    Err(Error::Domain(d))
                }
                Error::Fault(b) => {
                    if let Some(s) = &b.source {
                        if s.is::<S>() {
                            return Err(op(*b.source.unwrap().downcast::<S>().unwrap()).into());
                        }
                    }

                    Err(Error::Fault(b))
                }
            },
        }
    }

    fn with_context(self, context: impl Display) -> Result<T, Error<D>> {
        match self {
            Ok(ok) => Ok(ok),
            Err(error) => Err(match error {
                Error::Domain(explicit_error) => explicit_error.with_context(context).into(),
                Error::Fault(fault) => fault.with_context(context).into(),
            }),
        }
    }
}

/// To use this trait on [Option] import the prelude `use explicit_error::prelude::*`
pub trait OptionFault<T> {
    /// Transforms the `Option<T>` into a `Result<T, Fault>`, mapping Some(v) to Ok(v) and None to Err(Fault)
    /// ```rust
    /// # use std::fs::File;
    /// # use explicit_error_exit::{Error, prelude::*};
    /// fn foo() -> Result<(), Error> {
    ///     let option: Option<u8> = None;
    ///     option.ok_or_fault().with_context("Help debugging")?;
    ///     # Ok(())
    /// }
    /// ```
    fn ok_or_fault(self) -> Result<T, Fault>;

    /// Transforms the `Option<T>` into a `Result<T, Fault>`, mapping Some(v) to Ok(v) and None to Err(Fault)
    /// forcing backtrace capture
    /// ```rust
    /// # use std::fs::File;
    /// # use explicit_error_exit::{Error, prelude::*};
    /// fn foo() -> Result<(), Error> {
    ///     let option: Option<u8> = None;
    ///     option.ok_or_fault_force().with_context("Help debugging")?;
    ///     # Ok(())
    /// }
    /// ```
    fn ok_or_fault_force(self) -> Result<T, Fault>;
}

impl<T> OptionFault<T> for Option<T> {
    fn ok_or_fault(self) -> Result<T, Fault> {
        match self {
            Some(ok) => Ok(ok),
            None => Err(Fault::new()),
        }
    }

    fn ok_or_fault_force(self) -> Result<T, Fault> {
        match self {
            Some(ok) => Ok(ok),
            None => Err(Fault::new_force()),
        }
    }
}

/// To use this trait on [Result] import the prelude `use explicit_error::prelude::*`
pub trait ResultFaultWithContext<T> {
    /// Add a context to the [Fault] wrapped in a [Result::Err]
    /// # Examples
    /// ```rust
    /// # use explicit_error::{prelude::*, Fault};
    /// Err::<(), _>(Fault::new()).with_context("Foo bar");
    /// ```
    fn with_context(self, context: impl Display) -> Result<T, Fault>;
}

impl<T> ResultFaultWithContext<T> for Result<T, Fault> {
    fn with_context(self, context: impl Display) -> Result<T, Fault> {
        match self {
            Ok(ok) => Ok(ok),
            Err(b) => Err(b.with_context(context)),
        }
    }
}

#[cfg(test)]
mod test;