recoil 1.0.0

Error handling library for axum and anyhow.
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
#![doc = include_str!("../README.md")]

use anyhow::{format_err, Error};
use axum::{
    response::{IntoResponse, Response},
    Json,
};
use http::StatusCode;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Display};

/// Create a sequence of error messages, from a runtime error and optionally a message.
///
/// Messages are ordered last to first, following the chain of errors.
pub fn trace_error(message: Option<String>, error: Error) -> Vec<String> {
    let mut reasons = Vec::new();

    if let Some(head) = message {
        reasons.push(head);
    }
    reasons.push(error.to_string());

    error
        .chain()
        .skip(1)
        .for_each(|x| reasons.push(x.to_string()));
    reasons
}

/// The most basic structure of an error response, that can be serialized into a JSON body.
///
/// Has an implementation of `ErrorResponder`, and is ready out-of-the-box.
#[derive(Clone, Default, Deserialize, Serialize)]
pub struct Failure {
    /// Sequence of error messages.
    pub errors: Vec<String>,
}

/// Behavior for how a runtime error should be exported into an HTTP response, based on what information is available.
///
/// All methods (except the constructor) return `(StatusCode, Json<Self>)`, which implements `axum::response::IntoResponse`.
///
/// Individual implementations of `ErrorResponder` decide how to handle optional status codes,
/// usually `StatusCode::INTERNAL_SERVER_ERROR` is used.
pub trait ErrorResponder: Default + Serialize {
    /// Create a new error response.
    fn new() -> Self {
        Self::default()
    }

    /// Fail due to a runtime error, with an optional status code.
    ///
    /// Use when:
    /// * No context is available.
    /// * The context is included already when using `anyhow::Context`.
    fn fail(due_to: Error, status: Option<StatusCode>) -> (StatusCode, Json<Self>);

    /// Fail because of something, which occurred due to a runtime error, with an optional status code.
    ///
    /// Use when:
    /// * The context is available but not with `anyhow::Context`.
    /// * An overall context is relevant that is not included with `anyhow::Context`.
    fn fail_because(
        because: impl Display,
        due_to: Error,
        status: Option<StatusCode>,
    ) -> (StatusCode, Json<Self>);

    /// Fail because of something, with an optional status code.
    ///
    /// Use when:
    /// * No `anyhow::Error` is available.
    fn fail_directly(because: impl Display, status: Option<StatusCode>) -> (StatusCode, Json<Self>);

    /// Fail because of an internal server error, which occurred due to a runtime error, with status code 500.
    ///
    /// Use when:
    /// * No error handler exists, and a catch-all is needed.
    fn crash(due_to: Option<Error>) -> (StatusCode, Json<Self>);
}

impl ErrorResponder for Failure {
    fn fail(due_to: Error, status: Option<StatusCode>) -> (StatusCode, Json<Self>) {
        (
            if let Some(status) = status {
                status
            } else {
                StatusCode::INTERNAL_SERVER_ERROR
            },
            Json(Failure {
                errors: trace_error(None, due_to),
            }),
        )
    }

    fn fail_because(
        because: impl Display,
        due_to: Error,
        status: Option<StatusCode>,
    ) -> (StatusCode, Json<Self>) {
        (
            if let Some(status) = status {
                status
            } else {
                StatusCode::INTERNAL_SERVER_ERROR
            },
            Json(Failure {
                errors: trace_error(Some(because.to_string()), due_to),
            }),
        )
    }

    fn fail_directly(because: impl Display, status: Option<StatusCode>) -> (StatusCode, Json<Self>) {
        (
            if let Some(status) = status {
                status
            } else {
                StatusCode::INTERNAL_SERVER_ERROR
            },
            Json(Failure {
                errors: vec![because.to_string()],
            }),
        )
    }

    fn crash(due_to: Option<Error>) -> (StatusCode, Json<Self>) {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(Failure {
                errors: if let Some(error) = due_to {
                    trace_error(None, error)
                } else {
                    vec!["Server crashed due to unknown reasons.".to_owned()]
                },
            }),
        )
    }
}

/// Shared behavior of any type that can cause an error during runtime.
///
/// Implemented for `std::result::Result` and `std::option::Option` by default.
pub trait Fallible<T> {
    /// Check if `Self` is ok.
    fn has_not_failed(&self) -> bool;

    /// Get inner `T` of `Self`.
    fn get_inner(self) -> T;

    /// Get error.
    fn get_error(self) -> Error;
}
impl<T, E> Fallible<T> for Result<T, E>
where
    E: Debug + Display + Send + Sync + 'static,
{
    fn has_not_failed(&self) -> bool {
        self.is_ok()
    }

    fn get_inner(self) -> T {
        self.unwrap()
    }

    fn get_error(self) -> Error {
        format_err!(self.err().unwrap())
    }
}
impl<T> Fallible<T> for Option<T> {
    fn has_not_failed(&self) -> bool {
        self.is_some()
    }

    fn get_inner(self) -> T {
        self.unwrap()
    }

    fn get_error(self) -> Error {
        Error::msg("`Option` has `None` value.")
    }
}

/// Behavior for how types that implement `Fallible` should be exported into a HTTP response.
pub trait Recoil<T>: Fallible<T> {
    /// Return a `Result` that returns the original `T` if `Self` is ok,
    /// or a `Response` generated with the given responder if not.
    ///
    /// If the error responder is invoked, the methods `fail_because()` and `fail()` of the responder structure,
    /// will be called, depending on whether context was included, or excluded, respectively.
    fn recoil<R>(
        self,
        context: Option<impl Display + Send + Sync + 'static>,
        status: Option<StatusCode>,
    ) -> Result<T, Response>
    where
        R: ErrorResponder,
        Self: Sized,
    {
        if self.has_not_failed() {
            Ok(self.get_inner())
        } else {
            Err((if let Some(message) = context {
                R::fail_because(message.to_string(), self.get_error(), status)
            } else {
                R::fail(self.get_error(), status)
            })
            .into_response())
        }
    }
}

impl<T, E> Recoil<T> for Result<T, E> where E: Debug + Display + Send + Sync + 'static {}

impl<T> Recoil<T> for Option<T> {}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::response::IntoResponse;
    use http_body::Body;
    use serde_json::to_string as json_dumps;

    mod example {
        use anyhow::{bail, Context, Result};

        fn always_err() -> Result<()> {
            bail!("Never depend on me.");
        }

        pub fn dependent() -> Result<()> {
            always_err()?;
            Ok(())
        }

        pub fn with_context() -> Result<()> {
            always_err().context("Was giving someone else a chance.")
        }
    }

    #[test]
    fn tracing() {
        assert_eq!(
            trace_error(None, example::dependent().err().unwrap()).len(),
            1
        );

        {
            let message = "I can't trust anyone.";
            let errors = trace_error(
                Some(message.to_owned()),
                example::dependent().err().unwrap(),
            );
            assert_eq!(errors.len(), 2);
            assert_eq!(errors.get(0).unwrap(), message);
        }

        {
            let errors = trace_error(None, example::with_context().err().unwrap());
            assert_eq!(errors.len(), 2);
            assert_eq!(errors.get(0).unwrap(), "Was giving someone else a chance.");
        }
    }

    async fn response_generic(
        response: (StatusCode, Json<Failure>),
        expected_status: StatusCode,
        expected_errors: usize,
    ) {
        let body = response.1 .0.clone();

        assert_eq!(body.errors.len(), expected_errors);

        let mut res = response.into_response();

        assert_eq!(res.status(), expected_status);

        assert_eq!(
            String::from_utf8(res.body_mut().data().await.unwrap().unwrap().to_vec()).unwrap(),
            json_dumps(&body).unwrap()
        );
    }

    #[tokio::test]
    async fn response_fail() {
        response_generic(
            Failure::fail(example::with_context().err().unwrap(), None),
            StatusCode::INTERNAL_SERVER_ERROR,
            2,
        )
        .await;
    }

    #[tokio::test]
    async fn response_fail_with_code() {
        response_generic(
            Failure::fail(
                example::with_context().err().unwrap(),
                Some(StatusCode::IM_A_TEAPOT),
            ),
            StatusCode::IM_A_TEAPOT,
            2,
        )
        .await;
    }

    #[tokio::test]
    async fn response_fail_because() {
        response_generic(
            Failure::fail_because(
                "I missing working alone.".to_owned(),
                example::with_context().err().unwrap(),
                None,
            ),
            StatusCode::INTERNAL_SERVER_ERROR,
            3,
        )
        .await;
    }

    #[tokio::test]
    async fn response_fail_because_with_code() {
        response_generic(
            Failure::fail_because(
                "I missing working alone.".to_owned(),
                example::with_context().err().unwrap(),
                Some(StatusCode::IM_A_TEAPOT),
            ),
            StatusCode::IM_A_TEAPOT,
            3,
        )
        .await;
    }

    #[tokio::test]
    async fn response_fail_directly() {
        response_generic(
            Failure::fail_directly("I missing working alone.".to_owned(), None),
            StatusCode::INTERNAL_SERVER_ERROR,
            1,
        )
        .await;
    }

    #[tokio::test]
    async fn response_fail_directly_with_code() {
        response_generic(
            Failure::fail_directly(
                "I missing working alone.".to_owned(),
                Some(StatusCode::IM_A_TEAPOT),
            ),
            StatusCode::IM_A_TEAPOT,
            1,
        )
        .await;
    }

    #[tokio::test]
    async fn response_crash() {
        response_generic(
            Failure::crash(Some(example::with_context().err().unwrap())),
            StatusCode::INTERNAL_SERVER_ERROR,
            2,
        )
        .await;
    }

    #[tokio::test]
    async fn response_crash_blind() {
        response_generic(Failure::crash(None), StatusCode::INTERNAL_SERVER_ERROR, 1).await;
    }

    #[test]
    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: Never depend on me.")]
    fn fallible() {
        assert!(!example::dependent().has_not_failed());
        example::dependent().get_error();
        example::dependent().get_inner();
    }

    #[tokio::test]
    async fn recoil() {
        let result =
            example::dependent().recoil::<Failure>(Some("Nobody is coming to help us."), None);
        assert!(result.is_err());

        let mut res = result.err().unwrap();
        assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);

        assert_eq!(
            String::from_utf8(res.body_mut().data().await.unwrap().unwrap().to_vec()).unwrap(),
            json_dumps(
                &Failure::fail_because(
                    "Nobody is coming to help us.".to_owned(),
                    example::dependent().err().unwrap(),
                    None
                )
                .1
                 .0
            )
            .unwrap()
        );
    }
}