use serde_json::Value;
use crate::types::{GenerateResponse, RequestError};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("pain001 API returned HTTP {status}: {detail}")]
Api {
status: u16,
detail: Value,
},
#[error("pain001 API refused the file (HTTP {status}): {}", response.message)]
Refused {
status: u16,
response: Box<GenerateResponse>,
},
#[error("pain001 API request failed: {0}")]
Transport(#[source] Box<dyn std::error::Error + Send + Sync + 'static>),
#[error("pain001 API response could not be decoded: {0}")]
Decode(#[source] serde_json::Error),
}
impl Error {
pub fn status(&self) -> Option<u16> {
match self {
Error::Api { status, .. } | Error::Refused { status, .. } => Some(*status),
_ => None,
}
}
pub fn refusal(&self) -> Option<&GenerateResponse> {
match self {
Error::Refused { response, .. } => Some(response),
_ => None,
}
}
pub fn request_errors(&self) -> Option<Vec<RequestError>> {
match self {
Error::Api { detail, .. } if detail.is_array() => {
serde_json::from_value(detail.clone()).ok()
}
_ => None,
}
}
pub(crate) fn transport<E>(error: E) -> Self
where
E: std::error::Error + Send + Sync + 'static,
{
Error::Transport(Box::new(error))
}
}
pub(crate) fn generate_error(status: u16, body: Value) -> Error {
if status == 422 && body.get("success") == Some(&Value::Bool(false)) {
if let Ok(response) = serde_json::from_value::<GenerateResponse>(body.clone()) {
if response.xml.is_none() {
return Error::Refused {
status,
response: Box::new(response),
};
}
}
}
api_error(status, body)
}
pub(crate) fn generated(response: GenerateResponse) -> Result<GenerateResponse, Error> {
if response.success && response.xml.is_some() {
return Ok(response);
}
Err(Error::Decode(serde::de::Error::custom(
"a 2xx generate response must have success: true and the xml",
)))
}
pub(crate) fn api_error(status: u16, body: Value) -> Error {
let detail = match body {
Value::Object(mut map) if map.contains_key("detail") => {
map.remove("detail").unwrap_or(Value::Null)
}
other => other,
};
Error::Api { status, detail }
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn api_error_unwraps_the_detail_field() {
let error = api_error(400, json!({"detail": "bad IBAN"}));
assert_eq!(error.status(), Some(400));
assert!(matches!(error, Error::Api { detail, .. } if detail == json!("bad IBAN")));
}
#[test]
fn api_error_keeps_a_body_without_detail() {
let error = api_error(500, json!({"error": "boom"}));
assert!(matches!(error, Error::Api { detail, .. } if detail == json!({"error": "boom"})));
let error = api_error(502, json!("Bad Gateway"));
assert!(matches!(error, Error::Api { detail, .. } if detail == json!("Bad Gateway")));
}
#[test]
fn display_names_the_status_and_other_kinds_have_none() {
let error = api_error(404, json!({"detail": "Unknown face"}));
assert_eq!(
error.to_string(),
"pain001 API returned HTTP 404: \"Unknown face\""
);
let decode = serde_json::from_str::<u8>("x").unwrap_err();
assert_eq!(Error::Decode(decode).status(), None);
let io = std::io::Error::other("refused");
let transport = Error::transport(io);
assert_eq!(transport.status(), None);
assert!(std::error::Error::source(&transport).is_some());
assert!(transport.request_errors().is_none());
}
#[test]
fn generate_error_types_only_a_422_refusal_body() {
let refusal = json!({"success": false, "message": "Validation failed", "xml": null,
"validation_errors": [], "scheme_violations": []});
let error = generate_error(422, refusal.clone());
assert_eq!(error.status(), Some(422));
assert!(error.request_errors().is_none());
assert_eq!(error.refusal().map(|r| r.success), Some(false));
assert!(generate_error(400, refusal).refusal().is_none());
let success = generate_error(422, json!({"success": true, "message": "ok"}));
assert!(success.refusal().is_none());
let broken = generate_error(422, json!({"success": false}));
assert!(
matches!(broken, Error::Api { status: 422, detail } if detail == json!({"success": false}))
);
assert!(api_error(422, json!({})).refusal().is_none());
}
#[test]
fn a_refusal_body_that_carries_xml_stays_an_api_error() {
let body = json!({"success": false, "message": "m", "xml": "<x/>"});
let error = generate_error(422, body.clone());
assert!(matches!(error, Error::Api { status: 422, detail } if detail == body));
}
#[test]
fn request_errors_type_a_422_detail_array() {
let error = api_error(
422,
json!({"detail": [{"type": "enum", "loc": ["body", "message_type"],
"msg": "Input should be ...", "input": "pain.999"}]}),
);
let items = error.request_errors().expect("typed");
assert_eq!(items[0].kind, "enum");
assert_eq!(items[0].loc, [json!("body"), json!("message_type")]);
assert_eq!(items[0].ctx, None);
assert!(api_error(400, json!({"detail": "x"}))
.request_errors()
.is_none());
assert!(api_error(422, json!({"detail": [1]}))
.request_errors()
.is_none());
}
}