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
use std::fmt;

//
// Extension trait for Result types.
//

pub trait ResultExt<T, E> {
    /// Unwraps a result, yielding the content of an [`Ok`].
    ///
    /// # Panics
    ///
    /// Panics if the value is an [`Err`], logging a message provided by the
    /// [`Err`]'s value to a [`slog::Logger`] at a [`Critical`] level.
    fn unwrap_or_log(self, log: &slog::Logger) -> T
    where
        E: fmt::Debug;

    /// Unwraps a result, yielding the content of an [`Ok`].
    ///
    /// # Panics
    ///
    /// Panics if the value is an [`Err`], logging the passed message and the
    /// content of the [`Err`] to a [`slog::Logger`] at a [`Critical`] level.
    fn expect_or_log(self, log: &slog::Logger, msg: &str) -> T
    where
        E: fmt::Debug;

    /// Unwraps a result, yielding the content of an [`Err`].
    ///
    /// # Panics
    ///
    /// Panics if the value is an [`Ok`], logging a message provided by the
    /// [`Ok`]'s value to a [`slog::Logger`] at a [`Critical`] level.
    fn unwrap_err_or_log(self, log: &slog::Logger) -> E
    where
        T: fmt::Debug;

    /// Unwraps a result, yielding the content of an [`Err`].
    ///
    /// # Panics
    ///
    /// Panics if the value is an [`Ok`], logging the passed message and the
    /// content of the [`Ok`] to a [`slog::Logger`] at a [`Critical`] level.
    fn expect_err_or_log(self, log: &slog::Logger, msg: &str) -> E
    where
        T: fmt::Debug;
}

impl<T, E> ResultExt<T, E> for Result<T, E> {
    fn unwrap_or_log(self, log: &slog::Logger) -> T
    where
        E: fmt::Debug,
    {
        match self {
            Ok(t) => t,
            Err(e) => unwrap_failed(log, "called `Result::unwrap_log()` on an `Err` value", &e),
        }
    }

    fn expect_or_log(self, log: &slog::Logger, msg: &str) -> T
    where
        E: fmt::Debug,
    {
        match self {
            Ok(t) => t,
            Err(e) => unwrap_failed(log, msg, &e),
        }
    }

    fn unwrap_err_or_log(self, log: &slog::Logger) -> E
    where
        T: fmt::Debug,
    {
        match self {
            Ok(t) => unwrap_failed(
                log,
                "called `Result::unwrap_err_log()` on an `Ok` value",
                &t,
            ),
            Err(e) => e,
        }
    }

    fn expect_err_or_log(self, log: &slog::Logger, msg: &str) -> E
    where
        T: fmt::Debug,
    {
        match self {
            Ok(t) => unwrap_failed(log, msg, &t),
            Err(e) => e,
        }
    }
}

fn unwrap_failed(log: &slog::Logger, msg: &str, error: &dyn fmt::Debug) -> ! {
    slog::crit!(log, "{}: {:?}", msg, &error);
    panic!();
}