Skip to main content

brevo_rust/
error.rs

1use crate::prelude::*;
2use thiserror::Error;
3
4#[derive(Error, Debug)]
5pub enum ApiError {
6    #[error("BadRequestError: Bad request - {message}")]
7    BadRequestError {
8        message: String,
9        field: Option<String>,
10        details: Option<String>,
11    },
12    #[error("ForbiddenError: Access forbidden - {message}")]
13    ForbiddenError {
14        message: String,
15        resource: Option<String>,
16        required_permission: Option<String>,
17    },
18    #[error("NotFoundError: Resource not found - {message}")]
19    NotFoundError {
20        message: String,
21        resource_id: Option<String>,
22        resource_type: Option<String>,
23    },
24    #[error("InternalServerError: Internal server error - {message}")]
25    InternalServerError {
26        message: String,
27        error_id: Option<String>,
28    },
29    #[error("FailedDependencyError: {message}")]
30    FailedDependencyError { message: String },
31    #[error("TooManyRequestsError: Rate limit exceeded - {message}")]
32    TooManyRequestsError {
33        message: String,
34        code: Option<String>,
35    },
36    #[error("TooEarlyError: {message}")]
37    TooEarlyError {
38        message: String,
39        code: Option<ContactErrorModelCode>,
40        metadata: Option<HashMap<String, serde_json::Value>>,
41    },
42    #[error("ConflictError: Conflict - {message}")]
43    ConflictError {
44        message: String,
45        code: Option<String>,
46    },
47    #[error("MethodNotAllowedError: {message}")]
48    MethodNotAllowedError {
49        message: String,
50        code: Option<String>,
51    },
52    #[error("UnauthorizedError: Authentication failed - {message}")]
53    UnauthorizedError {
54        message: String,
55        auth_type: Option<String>,
56    },
57    #[error("UnprocessableEntityError: Unprocessable entity - {message}")]
58    UnprocessableEntityError {
59        message: String,
60        code: Option<String>,
61    },
62    #[error("PreconditionFailedError: {message}")]
63    PreconditionFailedError {
64        message: String,
65        code: Option<String>,
66    },
67    #[error("ExpectationFailedError: {message}")]
68    ExpectationFailedError {
69        message: String,
70        code: Option<String>,
71    },
72    #[error("PaymentRequiredError: {message}")]
73    PaymentRequiredError {
74        message: String,
75        code: Option<String>,
76    },
77    #[error("UnsupportedMediaTypeError: {message}")]
78    UnsupportedMediaTypeError {
79        message: String,
80        code: Option<String>,
81    },
82    #[error("HTTP error {status}: {message}")]
83    Http { status: u16, message: String },
84    #[error("Network error: {0}")]
85    Network(reqwest::Error),
86    #[error("Request executor error: {0}")]
87    Executor(Box<dyn std::error::Error + Send + Sync>),
88    #[error("Serialization error: {0}")]
89    Serialization(serde_json::Error),
90    #[error("Configuration error: {0}")]
91    Configuration(String),
92    #[error("Invalid header value")]
93    InvalidHeader,
94    #[error("Could not clone request for retry")]
95    RequestClone,
96    #[error("SSE stream terminated")]
97    StreamTerminated,
98    #[error("SSE stream timed out waiting for next event")]
99    StreamTimeout,
100    #[error("SSE parse error: {0}")]
101    SseParseError(String),
102}
103
104impl ApiError {
105    pub fn from_response(status_code: u16, body: Option<&str>) -> Self {
106        match status_code {
107            400 => {
108                // Parse error body for BadRequestError;
109                if let Some(body_str) = body {
110                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
111                        return Self::BadRequestError {
112                            message: parsed
113                                .get("message")
114                                .and_then(|v| v.as_str())
115                                .unwrap_or("Unknown error")
116                                .to_string(),
117                            field: parsed
118                                .get("field")
119                                .and_then(|v| v.as_str().map(|s| s.to_string())),
120                            details: parsed
121                                .get("details")
122                                .and_then(|v| v.as_str().map(|s| s.to_string())),
123                        };
124                    }
125                }
126                return Self::BadRequestError {
127                    message: body.unwrap_or("Unknown error").to_string(),
128                    field: None,
129                    details: None,
130                };
131            }
132            403 => {
133                // Parse error body for ForbiddenError;
134                if let Some(body_str) = body {
135                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
136                        return Self::ForbiddenError {
137                            message: parsed
138                                .get("message")
139                                .and_then(|v| v.as_str())
140                                .unwrap_or("Unknown error")
141                                .to_string(),
142                            resource: parsed
143                                .get("resource")
144                                .and_then(|v| v.as_str().map(|s| s.to_string())),
145                            required_permission: parsed
146                                .get("requiredPermission")
147                                .and_then(|v| v.as_str().map(|s| s.to_string())),
148                        };
149                    }
150                }
151                return Self::ForbiddenError {
152                    message: body.unwrap_or("Unknown error").to_string(),
153                    resource: None,
154                    required_permission: None,
155                };
156            }
157            404 => {
158                // Parse error body for NotFoundError;
159                if let Some(body_str) = body {
160                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
161                        return Self::NotFoundError {
162                            message: parsed
163                                .get("message")
164                                .and_then(|v| v.as_str())
165                                .unwrap_or("Unknown error")
166                                .to_string(),
167                            resource_id: parsed
168                                .get("resourceId")
169                                .and_then(|v| v.as_str().map(|s| s.to_string())),
170                            resource_type: parsed
171                                .get("resourceType")
172                                .and_then(|v| v.as_str().map(|s| s.to_string())),
173                        };
174                    }
175                }
176                return Self::NotFoundError {
177                    message: body.unwrap_or("Unknown error").to_string(),
178                    resource_id: None,
179                    resource_type: None,
180                };
181            }
182            500 => {
183                // Parse error body for InternalServerError;
184                if let Some(body_str) = body {
185                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
186                        return Self::InternalServerError {
187                            message: parsed
188                                .get("message")
189                                .and_then(|v| v.as_str())
190                                .unwrap_or("Unknown error")
191                                .to_string(),
192                            error_id: parsed
193                                .get("errorId")
194                                .and_then(|v| v.as_str().map(|s| s.to_string())),
195                        };
196                    }
197                }
198                return Self::InternalServerError {
199                    message: body.unwrap_or("Unknown error").to_string(),
200                    error_id: None,
201                };
202            }
203            424 => {
204                // Parse error body for FailedDependencyError;
205                if let Some(body_str) = body {
206                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
207                        return Self::FailedDependencyError {
208                            message: parsed
209                                .get("message")
210                                .and_then(|v| v.as_str())
211                                .unwrap_or("Unknown error")
212                                .to_string(),
213                        };
214                    }
215                }
216                return Self::FailedDependencyError {
217                    message: body.unwrap_or("Unknown error").to_string(),
218                };
219            }
220            429 => {
221                // Parse error body for TooManyRequestsError;
222                if let Some(body_str) = body {
223                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
224                        return Self::TooManyRequestsError {
225                            message: parsed
226                                .get("message")
227                                .and_then(|v| v.as_str())
228                                .unwrap_or("Unknown error")
229                                .to_string(),
230                            code: parsed
231                                .get("code")
232                                .and_then(|v| v.as_str().map(|s| s.to_string())),
233                        };
234                    }
235                }
236                return Self::TooManyRequestsError {
237                    message: body.unwrap_or("Unknown error").to_string(),
238                    code: None,
239                };
240            }
241            425 => {
242                // Parse error body for TooEarlyError;
243                if let Some(body_str) = body {
244                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
245                        return Self::TooEarlyError {
246                            message: parsed
247                                .get("message")
248                                .and_then(|v| v.as_str())
249                                .unwrap_or("Unknown error")
250                                .to_string(),
251                            code: parsed.get("code").and_then(|v| {
252                                serde_json::from_value::<ContactErrorModelCode>(v.clone()).ok()
253                            }),
254                            metadata: parsed.get("metadata").and_then(|v| {
255                                serde_json::from_value::<HashMap<String, serde_json::Value>>(
256                                    v.clone(),
257                                )
258                                .ok()
259                            }),
260                        };
261                    }
262                }
263                return Self::TooEarlyError {
264                    message: body.unwrap_or("Unknown error").to_string(),
265                    code: None,
266                    metadata: None,
267                };
268            }
269            409 => {
270                // Parse error body for ConflictError;
271                if let Some(body_str) = body {
272                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
273                        return Self::ConflictError {
274                            message: parsed
275                                .get("message")
276                                .and_then(|v| v.as_str())
277                                .unwrap_or("Unknown error")
278                                .to_string(),
279                            code: parsed
280                                .get("code")
281                                .and_then(|v| v.as_str().map(|s| s.to_string())),
282                        };
283                    }
284                }
285                return Self::ConflictError {
286                    message: body.unwrap_or("Unknown error").to_string(),
287                    code: None,
288                };
289            }
290            405 => {
291                // Parse error body for MethodNotAllowedError;
292                if let Some(body_str) = body {
293                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
294                        return Self::MethodNotAllowedError {
295                            message: parsed
296                                .get("message")
297                                .and_then(|v| v.as_str())
298                                .unwrap_or("Unknown error")
299                                .to_string(),
300                            code: parsed
301                                .get("code")
302                                .and_then(|v| v.as_str().map(|s| s.to_string())),
303                        };
304                    }
305                }
306                return Self::MethodNotAllowedError {
307                    message: body.unwrap_or("Unknown error").to_string(),
308                    code: None,
309                };
310            }
311            401 => {
312                // Parse error body for UnauthorizedError;
313                if let Some(body_str) = body {
314                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
315                        return Self::UnauthorizedError {
316                            message: parsed
317                                .get("message")
318                                .and_then(|v| v.as_str())
319                                .unwrap_or("Unknown error")
320                                .to_string(),
321                            auth_type: parsed
322                                .get("authType")
323                                .and_then(|v| v.as_str().map(|s| s.to_string())),
324                        };
325                    }
326                }
327                return Self::UnauthorizedError {
328                    message: body.unwrap_or("Unknown error").to_string(),
329                    auth_type: None,
330                };
331            }
332            422 => {
333                // Parse error body for UnprocessableEntityError;
334                if let Some(body_str) = body {
335                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
336                        return Self::UnprocessableEntityError {
337                            message: parsed
338                                .get("message")
339                                .and_then(|v| v.as_str())
340                                .unwrap_or("Unknown error")
341                                .to_string(),
342                            code: parsed
343                                .get("code")
344                                .and_then(|v| v.as_str().map(|s| s.to_string())),
345                        };
346                    }
347                }
348                return Self::UnprocessableEntityError {
349                    message: body.unwrap_or("Unknown error").to_string(),
350                    code: None,
351                };
352            }
353            412 => {
354                // Parse error body for PreconditionFailedError;
355                if let Some(body_str) = body {
356                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
357                        return Self::PreconditionFailedError {
358                            message: parsed
359                                .get("message")
360                                .and_then(|v| v.as_str())
361                                .unwrap_or("Unknown error")
362                                .to_string(),
363                            code: parsed
364                                .get("code")
365                                .and_then(|v| v.as_str().map(|s| s.to_string())),
366                        };
367                    }
368                }
369                return Self::PreconditionFailedError {
370                    message: body.unwrap_or("Unknown error").to_string(),
371                    code: None,
372                };
373            }
374            417 => {
375                // Parse error body for ExpectationFailedError;
376                if let Some(body_str) = body {
377                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
378                        return Self::ExpectationFailedError {
379                            message: parsed
380                                .get("message")
381                                .and_then(|v| v.as_str())
382                                .unwrap_or("Unknown error")
383                                .to_string(),
384                            code: parsed
385                                .get("code")
386                                .and_then(|v| v.as_str().map(|s| s.to_string())),
387                        };
388                    }
389                }
390                return Self::ExpectationFailedError {
391                    message: body.unwrap_or("Unknown error").to_string(),
392                    code: None,
393                };
394            }
395            402 => {
396                // Parse error body for PaymentRequiredError;
397                if let Some(body_str) = body {
398                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
399                        return Self::PaymentRequiredError {
400                            message: parsed
401                                .get("message")
402                                .and_then(|v| v.as_str())
403                                .unwrap_or("Unknown error")
404                                .to_string(),
405                            code: parsed
406                                .get("code")
407                                .and_then(|v| v.as_str().map(|s| s.to_string())),
408                        };
409                    }
410                }
411                return Self::PaymentRequiredError {
412                    message: body.unwrap_or("Unknown error").to_string(),
413                    code: None,
414                };
415            }
416            415 => {
417                // Parse error body for UnsupportedMediaTypeError;
418                if let Some(body_str) = body {
419                    if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(body_str) {
420                        return Self::UnsupportedMediaTypeError {
421                            message: parsed
422                                .get("message")
423                                .and_then(|v| v.as_str())
424                                .unwrap_or("Unknown error")
425                                .to_string(),
426                            code: parsed
427                                .get("code")
428                                .and_then(|v| v.as_str().map(|s| s.to_string())),
429                        };
430                    }
431                }
432                return Self::UnsupportedMediaTypeError {
433                    message: body.unwrap_or("Unknown error").to_string(),
434                    code: None,
435                };
436            }
437            _ => Self::Http {
438                status: status_code,
439                message: body.unwrap_or("Unknown error").to_string(),
440            },
441        }
442    }
443}
444
445/// Error returned when a required field was not set on a builder.
446#[derive(Debug)]
447pub struct BuildError {
448    field: &'static str,
449}
450
451impl BuildError {
452    pub fn missing_field(field: &'static str) -> Self {
453        Self { field }
454    }
455}
456
457impl std::fmt::Display for BuildError {
458    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
459        write!(f, "`{}` was not set but is required", self.field)
460    }
461}
462
463impl std::error::Error for BuildError {}