Skip to main content

pain001_sdk/
error.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2//! The one error type every client call returns.
3
4use serde_json::Value;
5
6use crate::types::{GenerateResponse, RequestError};
7
8/// What went wrong with a call.
9#[derive(Debug, thiserror::Error)]
10#[non_exhaustive]
11pub enum Error {
12    /// The server answered with a non-2xx status.
13    ///
14    /// `detail` is the response's `detail` field when the body is a JSON
15    /// object that has one (a string, or an array of field errors for a
16    /// `422`), the whole JSON body otherwise, or the raw text as a JSON
17    /// string when the body is not JSON.
18    #[error("pain001 API returned HTTP {status}: {detail}")]
19    Api {
20        /// The HTTP status code.
21        status: u16,
22        /// The server's explanation, parsed from the body.
23        detail: Value,
24    },
25    /// The server refused to generate a document: a `422` from a generate
26    /// call whose body is a [`GenerateResponse`] with `success: false` and
27    /// no `xml`.
28    ///
29    /// `response` carries the findings, typed: `validation_errors` for rows
30    /// that failed field checks and `scheme_violations` for scheme-rulebook
31    /// breaches. [`Error::status`] still returns the HTTP status.
32    #[error("pain001 API refused the file (HTTP {status}): {}", response.message)]
33    Refused {
34        /// The HTTP status code, `422`.
35        status: u16,
36        /// The decoded refusal, with `success: false` and no `xml`.
37        response: Box<GenerateResponse>,
38    },
39    /// The request did not complete: connection refused, timeout, TLS,
40    /// an invalid URL, or a body that could not be read.
41    #[error("pain001 API request failed: {0}")]
42    Transport(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
43    /// A 2xx response body did not match the expected shape.
44    #[error("pain001 API response could not be decoded: {0}")]
45    Decode(#[source] serde_json::Error),
46}
47
48impl Error {
49    /// The HTTP status for [`Error::Api`], `None` for the other kinds.
50    pub fn status(&self) -> Option<u16> {
51        match self {
52            Error::Api { status, .. } | Error::Refused { status, .. } => Some(*status),
53            _ => None,
54        }
55    }
56
57    /// The refused generation for [`Error::Refused`], `None` for the other
58    /// kinds: its `validation_errors` and `scheme_violations` say why.
59    pub fn refusal(&self) -> Option<&GenerateResponse> {
60        match self {
61            Error::Refused { response, .. } => Some(response),
62            _ => None,
63        }
64    }
65
66    /// The items of a `422` response's `detail` array, typed: `Some` only
67    /// for [`Error::Api`] whose `detail` is an array of FastAPI request
68    /// errors (for example an unknown message type).
69    pub fn request_errors(&self) -> Option<Vec<RequestError>> {
70        match self {
71            Error::Api { detail, .. } if detail.is_array() => {
72                serde_json::from_value(detail.clone()).ok()
73            }
74            _ => None,
75        }
76    }
77
78    pub(crate) fn transport<E>(error: E) -> Self
79    where
80        E: std::error::Error + Send + Sync + 'static,
81    {
82        Error::Transport(Box::new(error))
83    }
84}
85
86/// Builds the error for a non-2xx reply to a generate call: a `422` whose
87/// body decodes as a [`GenerateResponse`] with `success: false` and no
88/// `xml` becomes [`Error::Refused`], anything else goes through
89/// [`api_error`].
90pub(crate) fn generate_error(status: u16, body: Value) -> Error {
91    if status == 422 && body.get("success") == Some(&Value::Bool(false)) {
92        if let Ok(response) = serde_json::from_value::<GenerateResponse>(body.clone()) {
93            if response.xml.is_none() {
94                return Error::Refused {
95                    status,
96                    response: Box::new(response),
97                };
98            }
99        }
100    }
101    api_error(status, body)
102}
103
104/// Checks a decoded 2xx reply to a generate call: it must report
105/// `success: true` and carry the XML, so an `Ok` always has a document.
106/// Anything else is [`Error::Decode`].
107pub(crate) fn generated(response: GenerateResponse) -> Result<GenerateResponse, Error> {
108    if response.success && response.xml.is_some() {
109        return Ok(response);
110    }
111    Err(Error::Decode(serde::de::Error::custom(
112        "a 2xx generate response must have success: true and the xml",
113    )))
114}
115
116/// Builds [`Error::Api`] from a non-2xx status and its parsed body.
117pub(crate) fn api_error(status: u16, body: Value) -> Error {
118    let detail = match body {
119        Value::Object(mut map) if map.contains_key("detail") => {
120            map.remove("detail").unwrap_or(Value::Null)
121        }
122        other => other,
123    };
124    Error::Api { status, detail }
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use serde_json::json;
131
132    #[test]
133    fn api_error_unwraps_the_detail_field() {
134        let error = api_error(400, json!({"detail": "bad IBAN"}));
135        assert_eq!(error.status(), Some(400));
136        assert!(matches!(error, Error::Api { detail, .. } if detail == json!("bad IBAN")));
137    }
138
139    #[test]
140    fn api_error_keeps_a_body_without_detail() {
141        let error = api_error(500, json!({"error": "boom"}));
142        assert!(matches!(error, Error::Api { detail, .. } if detail == json!({"error": "boom"})));
143        let error = api_error(502, json!("Bad Gateway"));
144        assert!(matches!(error, Error::Api { detail, .. } if detail == json!("Bad Gateway")));
145    }
146
147    #[test]
148    fn display_names_the_status_and_other_kinds_have_none() {
149        let error = api_error(404, json!({"detail": "Unknown face"}));
150        assert_eq!(
151            error.to_string(),
152            "pain001 API returned HTTP 404: \"Unknown face\""
153        );
154        let decode = serde_json::from_str::<u8>("x").unwrap_err();
155        assert_eq!(Error::Decode(decode).status(), None);
156        let io = std::io::Error::other("refused");
157        let transport = Error::transport(io);
158        assert_eq!(transport.status(), None);
159        assert!(std::error::Error::source(&transport).is_some());
160        assert!(transport.request_errors().is_none());
161    }
162
163    #[test]
164    fn generate_error_types_only_a_422_refusal_body() {
165        let refusal = json!({"success": false, "message": "Validation failed", "xml": null,
166                             "validation_errors": [], "scheme_violations": []});
167        let error = generate_error(422, refusal.clone());
168        assert_eq!(error.status(), Some(422));
169        assert!(error.request_errors().is_none());
170        assert_eq!(error.refusal().map(|r| r.success), Some(false));
171        // Another status, a success body, or a shape that does not decode
172        // keeps the plain API error with the whole body.
173        assert!(generate_error(400, refusal).refusal().is_none());
174        let success = generate_error(422, json!({"success": true, "message": "ok"}));
175        assert!(success.refusal().is_none());
176        let broken = generate_error(422, json!({"success": false}));
177        assert!(
178            matches!(broken, Error::Api { status: 422, detail } if detail == json!({"success": false}))
179        );
180        assert!(api_error(422, json!({})).refusal().is_none());
181    }
182
183    #[test]
184    fn a_refusal_body_that_carries_xml_stays_an_api_error() {
185        // The `error` fuzz target checks this: `Refused` documents its
186        // response as having `success: false` and no `xml`.
187        let body = json!({"success": false, "message": "m", "xml": "<x/>"});
188        let error = generate_error(422, body.clone());
189        assert!(matches!(error, Error::Api { status: 422, detail } if detail == body));
190    }
191
192    #[test]
193    fn request_errors_type_a_422_detail_array() {
194        let error = api_error(
195            422,
196            json!({"detail": [{"type": "enum", "loc": ["body", "message_type"],
197                               "msg": "Input should be ...", "input": "pain.999"}]}),
198        );
199        let items = error.request_errors().expect("typed");
200        assert_eq!(items[0].kind, "enum");
201        assert_eq!(items[0].loc, [json!("body"), json!("message_type")]);
202        assert_eq!(items[0].ctx, None);
203        assert!(api_error(400, json!({"detail": "x"}))
204            .request_errors()
205            .is_none());
206        assert!(api_error(422, json!({"detail": [1]}))
207            .request_errors()
208            .is_none());
209    }
210}