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
//! # Standard Error Handling Types Extensions
//!
//! This module provides traits that extends the common error
//! handling types `Result` and `Option` with methods that
//! integrate them with the types defined in this crate.
use std::error::Error;

#[cfg(feature = "diesel")]
use crate::sql::NoRowsFound;
use crate::{
    http::{self, NotFound},
    Result,
};

mod sealed {
    pub trait Sealed {
        type Value;
    }

    impl<T, E> Sealed for Result<T, E> {
        type Value = T;
    }

    impl<T> Sealed for Option<T> {
        type Value = T;
    }
}

/// Extension methods on [`Result`].
///
/// [`Result`]: std::result::Result
pub trait ResultExt: sealed::Sealed + Sized {
    /// Converts this result to an internal error.
    ///
    /// Used when an unrecoverable error happens.
    ///
    /// See [`internal_error`] for more information.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `self` is `Err`.
    ///
    /// [`internal_error`]: crate::http::internal_error
    fn internal(self) -> Result<Self::Value>;
}

impl<T, E> ResultExt for Result<T, E>
where
    E: Error + Send + Sync + 'static,
{
    #[track_caller]
    fn internal(self) -> Result<Self::Value> {
        self.map_err(http::internal_error)
    }
}

/// Extension methods on `Result<T, Problem>`.
pub trait ProblemResultExt: ResultExt {
    /// Catch a specific error type `E`.
    ///
    /// Returns `Ok(Ok(_))` when the source `Result<T>` is a `T`, returns
    /// `Ok(Err(_))` when its is a `Problem` that can downcast to an `E`,
    /// and returns `Err(_)` otherwise.
    ///
    /// Useful when there is a need to handle a specific error differently,
    /// e.g. a [`NotFound`] error.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `self` contains a [`Problem`] which is not an `E`.
    ///
    /// [`Problem`]: crate::Problem
    /// [`NotFound`]: crate::http::NotFound
    fn catch_err<E>(self) -> Result<Result<Self::Value, E>>
    where
        E: Error + Send + Sync + 'static;

    /// Catch a [`NotFound`] and convert it to `None`.
    ///
    /// # Errors
    ///
    /// Returns `Err` if `self` contains a [`Problem`] which is not a
    /// [`NotFound`].
    ///
    /// [`Problem`]: crate::Problem
    /// [`NotFound`]: crate::http::NotFound
    fn optional(self) -> Result<Option<Self::Value>>;
}

impl<T> ProblemResultExt for Result<T> {
    fn catch_err<E>(self) -> Result<Result<Self::Value, E>>
    where
        E: Error + Send + Sync + 'static,
    {
        Ok(match self {
            Ok(ok) => Ok(ok),
            Err(err) => Err(err.downcast::<E>()?),
        })
    }

    fn optional(self) -> Result<Option<Self::Value>> {
        match self {
            Ok(ok) => Ok(Some(ok)),
            Err(err) => {
                if let Err(err) = err.downcast::<NotFound>() {
                    #[cfg(feature = "diesel")]
                    err.downcast::<NoRowsFound>()?;
                    #[cfg(not(feature = "diesel"))]
                    return Err(err);
                }

                Ok(None)
            }
        }
    }
}

/// Extension methods on `Option<T>`.
pub trait OptionExt: sealed::Sealed + Sized {
    /// Returns `Ok(_)` if the source is `Some(_)`, otherwise, returns a
    /// `Problem` that can downcast to `NotFound`.
    ///
    /// # Errors
    ///
    /// Returns `Err` when `self` is `None`.
    fn or_not_found<I>(self, entity: &'static str, identifier: I) -> Result<Self::Value>
    where
        I: std::fmt::Display;

    /// It's a wrapper to `or_not_found` to be used when
    /// there is no a specific identifier to entity message.
    ///
    /// Returns `Ok(_)` if the source is `Some(_)`, otherwise, returns a
    /// `Problem` that can downcast to `NotFound`.
    ///
    /// # Errors
    ///
    /// Returns `Err` when `self` is `None`.
    fn or_not_found_unknown(self, entity: &'static str) -> Result<Self::Value>;
}

impl<T> OptionExt for Option<T> {
    #[track_caller]
    fn or_not_found<I>(self, entity: &'static str, identifier: I) -> Result<Self::Value>
    where
        I: std::fmt::Display,
    {
        // Cannot use Option::ok_or_else as it isn't annotated with track_caller.
        if let Some(value) = self {
            Ok(value)
        } else {
            Err(http::not_found(entity, identifier))
        }
    }

    #[track_caller]
    fn or_not_found_unknown(self, entity: &'static str) -> Result<Self::Value> {
        self.or_not_found(entity, "<unknown>")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http;

    #[test]
    fn test_internal() {
        let res =
            Err(std::io::Error::new(std::io::ErrorKind::Other, "oh no")) as std::io::Result<()>;

        let res = res.internal().unwrap_err();

        assert!(res.is::<http::InternalError>());
    }

    #[test]
    fn test_catch_err() {
        let res =
            Err(std::io::Error::new(std::io::ErrorKind::Other, "oh no")) as std::io::Result<()>;

        let res = res.internal();

        let not_found = res.catch_err::<http::NotFound>().unwrap_err();
        let res = Err(not_found) as crate::Result<()>;

        let res = res.catch_err::<http::InternalError>().unwrap();

        assert!(res.is_err());

        let ok = Ok(()) as crate::Result<()>;

        assert!(ok.catch_err::<http::InternalError>().unwrap().is_ok());
    }

    #[test]
    fn test_optional() {
        let res = Err(http::not_found("user", "bla")) as crate::Result<()>;
        assert!(res.optional().unwrap().is_none());

        let res = Err(http::failed_precondition()) as crate::Result<()>;
        assert!(res.optional().is_err());

        let res = Ok(()) as crate::Result<()>;
        assert!(res.optional().unwrap().is_some());
    }

    #[test]
    fn test_or_not_found() {
        let res = None.or_not_found_unknown("bla") as crate::Result<()>;
        let err = res.unwrap_err();

        assert!(err.is::<http::NotFound>());

        let res = Some(()).or_not_found_unknown("bla");

        assert!(res.is_ok());
    }
}