Skip to main content

churchtools_api/
error.rs

1use serde::Deserialize;
2
3pub type Result<T> = std::result::Result<T, Error>;
4
5/// Everything that can go wrong with a request.
6///
7/// New variants may be added in minor versions, so a `match` needs a `_` arm.
8/// For the common checks there are helpers like [`Error::is_not_found`].
9#[derive(thiserror::Error)]
10#[non_exhaustive]
11pub enum Error {
12    /// The server answered with a non-2xx status.
13    #[error("{0}")]
14    Api(Box<ApiError>),
15    /// The request did not reach the server or the response could not be read.
16    #[error("transport error: {0}")]
17    Transport(#[source] TransportError),
18    /// The response body could not be read completely.
19    #[error("could not read response body: {0}")]
20    Read(#[source] std::io::Error),
21    /// The response body is larger than `ClientBuilder::max_response_size`.
22    #[error("response body larger than the limit of {limit} bytes")]
23    ResponseTooLarge { limit: u64 },
24    /// The response body did not match the expected shape.
25    #[error("could not decode response: {source}")]
26    Decode {
27        #[source]
28        source: serde_json::Error,
29        /// Response body (lossy UTF-8) for debugging.
30        body: String,
31    },
32    #[error("invalid base URL: {0}")]
33    InvalidBaseUrl(String),
34    /// The server answered with a redirect that is not followed (301, 302,
35    /// 303: it would repeat the request as GET without its body).
36    #[error("unexpected redirect (HTTP {status}) to {}", .location.as_deref().unwrap_or("<no location>"))]
37    Redirect { status: u16, location: Option<String> },
38    /// The token contains characters not allowed in an HTTP header.
39    #[error("invalid token: contains characters not allowed in an HTTP header")]
40    InvalidToken,
41    /// A path parameter was empty, `.` or `..`; the request was not sent.
42    #[error("invalid path (empty, `.` or `..` segment): {0}")]
43    InvalidPath(String),
44}
45
46/// Longest part of a response body shown by `Debug`; bodies may contain
47/// personal data and end up in logs. The full body stays in the field.
48const BODY_PREVIEW: usize = 300;
49
50struct Preview<'a>(&'a [u8]);
51
52impl std::fmt::Debug for Preview<'_> {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        let text = String::from_utf8_lossy(&self.0[..self.0.len().min(BODY_PREVIEW)]);
55        if self.0.len() > BODY_PREVIEW {
56            write!(f, "{text:?}… ({} bytes)", self.0.len())
57        } else {
58            write!(f, "{text:?}")
59        }
60    }
61}
62
63impl std::fmt::Debug for Error {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        match self {
66            Self::Api(api) => f.debug_tuple("Api").field(api).finish(),
67            Self::Transport(err) => f.debug_tuple("Transport").field(err).finish(),
68            Self::Decode { source, body } => f
69                .debug_struct("Decode")
70                .field("source", source)
71                .field("body", &Preview(body.as_bytes()))
72                .finish(),
73            Self::Read(err) => f.debug_tuple("Read").field(err).finish(),
74            Self::ResponseTooLarge { limit } => f.debug_struct("ResponseTooLarge").field("limit", limit).finish(),
75            Self::InvalidBaseUrl(url) => f.debug_tuple("InvalidBaseUrl").field(url).finish(),
76            Self::Redirect { status, location } => f
77                .debug_struct("Redirect")
78                .field("status", status)
79                .field("location", location)
80                .finish(),
81            Self::InvalidToken => f.write_str("InvalidToken"),
82            Self::InvalidPath(path) => f.debug_tuple("InvalidPath").field(path).finish(),
83        }
84    }
85}
86
87impl Error {
88    /// The error response of the server, if it answered with a non-2xx status.
89    pub fn api(&self) -> Option<&ApiError> {
90        match self {
91            Self::Api(api) => Some(api),
92            _ => None,
93        }
94    }
95
96    /// HTTP status of an error response or an unfollowed redirect.
97    pub fn status(&self) -> Option<u16> {
98        match self {
99            Self::Api(api) => Some(api.status),
100            Self::Redirect { status, .. } => Some(*status),
101            _ => None,
102        }
103    }
104
105    /// `404 Not Found`: the object does not exist or the person may not see it.
106    pub fn is_not_found(&self) -> bool {
107        self.status() == Some(404)
108    }
109
110    /// `401 Unauthorized`: no token, or an expired one.
111    pub fn is_unauthorized(&self) -> bool {
112        self.status() == Some(401)
113    }
114
115    /// `403 Forbidden`: logged in, but without permission.
116    pub fn is_forbidden(&self) -> bool {
117        self.status() == Some(403)
118    }
119
120    /// The request took longer than the timeout.
121    pub fn is_timeout(&self) -> bool {
122        matches!(self, Self::Transport(e) if e.is_timeout())
123    }
124
125    /// No connection to the server (wrong address, network down, connect timeout).
126    pub fn is_connect(&self) -> bool {
127        matches!(self, Self::Transport(e) if e.is_connect())
128    }
129}
130
131impl From<ApiError> for Error {
132    fn from(err: ApiError) -> Self {
133        Self::Api(Box::new(err))
134    }
135}
136
137impl Error {
138    pub(crate) fn transport(err: reqwest::Error) -> Self {
139        Self::Transport(TransportError(err))
140    }
141}
142
143/// Error of the HTTP layer: connection, TLS, timeout, or reading the response.
144///
145/// Wraps the error of the HTTP library, which is not part of this crate's
146/// public API; use the `is_*` helpers or `Display`/`source()`.
147pub struct TransportError(reqwest::Error);
148
149impl TransportError {
150    /// The request took longer than the timeout.
151    pub fn is_timeout(&self) -> bool {
152        self.0.is_timeout()
153    }
154
155    /// No connection to the server (wrong address, network down, connect timeout).
156    pub fn is_connect(&self) -> bool {
157        self.0.is_connect()
158    }
159}
160
161impl std::fmt::Display for TransportError {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        self.0.fmt(f)
164    }
165}
166
167impl std::fmt::Debug for TransportError {
168    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
169        self.0.fmt(f)
170    }
171}
172
173impl std::error::Error for TransportError {
174    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
175        self.0.source()
176    }
177}
178
179/// Error response of the ChurchTools API.
180///
181/// ChurchTools reports errors as
182/// `{"message", "translatedMessage", "messageKey", "args", "errors"}`;
183/// all fields are optional here because not every error path fills them.
184#[derive(Clone, thiserror::Error)]
185#[error("HTTP {status}: {}", .message.as_deref().unwrap_or("<no message>"))]
186pub struct ApiError {
187    pub status: u16,
188    pub message: Option<String>,
189    pub translated_message: Option<String>,
190    pub message_key: Option<String>,
191    pub args: serde_json::Value,
192    pub errors: serde_json::Value,
193    /// Raw response body.
194    pub body: Vec<u8>,
195}
196
197impl std::fmt::Debug for ApiError {
198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199        f.debug_struct("ApiError")
200            .field("status", &self.status)
201            .field("message", &self.message)
202            .field("translated_message", &self.translated_message)
203            .field("message_key", &self.message_key)
204            .field("args", &self.args)
205            .field("errors", &self.errors)
206            .field("body", &Preview(&self.body))
207            .finish()
208    }
209}
210
211#[derive(Deserialize, Default)]
212#[serde(rename_all = "camelCase", default)]
213struct ErrorBody {
214    message: Option<String>,
215    translated_message: Option<String>,
216    message_key: Option<String>,
217    args: serde_json::Value,
218    errors: serde_json::Value,
219}
220
221impl ApiError {
222    pub fn from_response(status: u16, body: Vec<u8>) -> Self {
223        let parsed: ErrorBody = serde_json::from_slice(&body).unwrap_or_default();
224        Self {
225            status,
226            message: parsed.message,
227            translated_message: parsed.translated_message,
228            message_key: parsed.message_key,
229            args: parsed.args,
230            errors: parsed.errors,
231            body,
232        }
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn helpers_classify_errors() {
242        let not_found = Error::from(ApiError::from_response(404, br#"{"message":"nope"}"#.to_vec()));
243        assert!(not_found.is_not_found() && !not_found.is_forbidden());
244        assert_eq!(not_found.api().and_then(|a| a.message.as_deref()), Some("nope"));
245        let redirect = Error::Redirect { status: 302, location: None };
246        assert_eq!((redirect.status(), redirect.api().is_none()), (Some(302), true));
247        assert_eq!(Error::InvalidToken.status(), None);
248    }
249
250    #[test]
251    fn debug_shortens_long_bodies() {
252        let body = format!(r#"{{"data":[{}]}}"#, r#"{"email":"anna@example.org"},"#.repeat(100));
253        let err = crate::decode::<i64>(body.as_bytes()).unwrap_err();
254        let debug = format!("{err:?}");
255        assert!(debug.len() < 1000, "{debug}");
256        assert!(debug.contains(&format!("({} bytes)", body.len())));
257        let Error::Decode { body: full, .. } = &err else { panic!() };
258        assert_eq!(full.len(), body.len()); // the field keeps everything
259
260        let api = ApiError::from_response(500, body.into_bytes());
261        assert!(format!("{api:?}").len() < 1000);
262        let short = ApiError::from_response(404, br#"{"message":"nope"}"#.to_vec());
263        assert!(format!("{short:?}").contains(r#"body: "{\"message\":\"nope\"}""#));
264    }
265}