axum_error_object/
context.rs

1use crate::ErrorResponse;
2
3pub trait Context<T> {
4    #[inline]
5    fn context<C>(self, context: C) -> crate::Result<T>
6    where
7        Self: Sized,
8        C: Into<ErrorResponse>,
9    {
10        self.with_context(move || context)
11    }
12
13    fn with_context<C>(self, context: impl FnOnce() -> C) -> crate::Result<T>
14    where
15        C: Into<ErrorResponse>;
16}
17
18impl<T, E> Context<T> for Result<T, E>
19where
20    E: Into<anyhow::Error>,
21{
22    fn with_context<C>(self, context: impl FnOnce() -> C) -> crate::Result<T>
23    where
24        C: Into<ErrorResponse>,
25    {
26        match self {
27            Ok(value) => Ok(value),
28            Err(error) => Err(context().into().with_source(error.into())),
29        }
30    }
31}
32
33impl<T> Context<T> for Option<T> {
34    fn with_context<C>(self, context: impl FnOnce() -> C) -> crate::Result<T>
35    where
36        C: Into<ErrorResponse>,
37    {
38        match self {
39            Some(value) => Ok(value),
40            None => Err(context().into()),
41        }
42    }
43}