Skip to main content

bachs_sdk/
error.rs

1use serde::Deserialize;
2use std::fmt;
3
4/// A single field-level validation error, as returned in the `errors` array
5/// of a `400 VALIDATION_ERROR` response.
6#[derive(Debug, Clone, Deserialize)]
7pub struct FieldError {
8    pub field: String,
9    pub message: String,
10    #[serde(rename = "type")]
11    pub error_type: String,
12}
13
14/// The flat error body every Bachs API error response shares:
15/// `{ "detail", "error_code", "doc_url"?, "errors"? }`.
16#[derive(Debug, Clone, Deserialize)]
17pub struct ApiErrorBody {
18    pub detail: String,
19    pub error_code: String,
20    #[serde(default)]
21    pub doc_url: Option<String>,
22    #[serde(default)]
23    pub errors: Vec<FieldError>,
24}
25
26impl fmt::Display for ApiErrorBody {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(f, "{} ({})", self.detail, self.error_code)?;
29        for e in &self.errors {
30            write!(f, "\n  - {}: {}", e.field, e.message)?;
31        }
32        Ok(())
33    }
34}
35
36/// Top-level error type returned by every fallible call in this SDK.
37#[derive(Debug, thiserror::Error)]
38pub enum BachsError {
39    /// The API returned a non-2xx response with a parsed `ApiErrorBody`.
40    #[error("Bachs API error [{status}]: {body}")]
41    Api {
42        status: u16,
43        body: ApiErrorBody,
44        /// Value of the `X-RateLimit-Reset` header, when present (Unix timestamp).
45        rate_limit_reset: Option<i64>,
46    },
47
48    /// The API returned a non-2xx response whose body could not be parsed
49    /// as the standard error shape.
50    #[error("Bachs API error [{status}]: {raw_body}")]
51    ApiUnparsed { status: u16, raw_body: String },
52
53    /// Networking / transport failure (DNS, TLS, timeout, connection reset, ...).
54    #[error("request failed: {0}")]
55    Request(#[from] reqwest::Error),
56
57    /// Failed to (de)serialize a request or response body.
58    #[error("(de)serialization error: {0}")]
59    Serialization(#[from] serde_json::Error),
60
61    /// Failed to build a valid request URL.
62    #[error("invalid URL: {0}")]
63    Url(#[from] url::ParseError),
64
65    /// Webhook signature verification failed.
66    #[error("webhook signature verification failed: {0}")]
67    WebhookSignature(String),
68
69    /// A programmer error building the request (e.g. an invalid header value).
70    #[error("invalid request: {0}")]
71    InvalidRequest(String),
72}
73
74pub type BachsResult<T> = Result<T, BachsError>;
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79
80    #[test]
81    fn api_error_body_display() {
82        let body = ApiErrorBody {
83            detail: "Invalid request".into(),
84            error_code: "VALIDATION_ERROR".into(),
85            doc_url: None,
86            errors: vec![FieldError {
87                field: "email".into(),
88                message: "must be a valid email".into(),
89                error_type: "value_error".into(),
90            }],
91        };
92        let s = format!("{}", body);
93        assert!(s.contains("Invalid request"));
94        assert!(s.contains("VALIDATION_ERROR"));
95        assert!(s.contains("email: must be a valid email"));
96    }
97
98    #[test]
99    fn api_error_body_display_no_field_errors() {
100        let body = ApiErrorBody {
101            detail: "Not found".into(),
102            error_code: "NOT_FOUND".into(),
103            doc_url: Some("https://docs.bachs.io/errors/not_found".into()),
104            errors: vec![],
105        };
106        let s = format!("{}", body);
107        assert!(s.contains("Not found"));
108        assert!(s.contains("NOT_FOUND"));
109        assert!(!s.contains("-"));
110    }
111
112    #[test]
113    fn bachs_error_api_display() {
114        let err = BachsError::Api {
115            status: 400,
116            body: ApiErrorBody {
117                detail: "Bad request".into(),
118                error_code: "BAD_REQUEST".into(),
119                doc_url: None,
120                errors: vec![],
121            },
122            rate_limit_reset: None,
123        };
124        let s = format!("{err}");
125        assert!(s.contains("[400]"));
126        assert!(s.contains("Bad request"));
127    }
128
129    #[test]
130    fn bachs_error_api_unparsed_display() {
131        let err = BachsError::ApiUnparsed {
132            status: 500,
133            raw_body: "internal server error".into(),
134        };
135        let s = format!("{err}");
136        assert!(s.contains("[500]"));
137        assert!(s.contains("internal server error"));
138    }
139
140    #[test]
141    fn bachs_error_webhook_signature_display() {
142        let err = BachsError::WebhookSignature("bad sig".into());
143        let s = format!("{err}");
144        assert!(s.contains("bad sig"));
145    }
146
147    #[test]
148    fn bachs_error_invalid_request_display() {
149        let err = BachsError::InvalidRequest("bad header".into());
150        let s = format!("{err}");
151        assert!(s.contains("bad header"));
152    }
153
154    #[test]
155    fn api_error_body_deserialization_with_all_fields() {
156        let json = r#"{
157            "detail": "something went wrong",
158            "error_code": "INTERNAL_ERROR",
159            "doc_url": "https://docs.bachs.io/errors/internal",
160            "errors": [
161                {"field": "amount", "message": "must be positive", "type": "value_error"}
162            ]
163        }"#;
164        let body: ApiErrorBody = serde_json::from_str(json).unwrap();
165        assert_eq!(body.detail, "something went wrong");
166        assert_eq!(body.error_code, "INTERNAL_ERROR");
167        assert_eq!(body.doc_url.as_deref(), Some("https://docs.bachs.io/errors/internal"));
168        assert_eq!(body.errors.len(), 1);
169        assert_eq!(body.errors[0].field, "amount");
170    }
171}