1use reqwest::StatusCode;
2use std::collections::HashMap;
3use std::{error::Error, fmt};
4
5#[derive(Debug)]
6pub enum ApiErrorType {
7 BadJson(String),
8 FailedRequest(String),
9 Error(String),
10 Status(StatusCode, String),
13}
14
15#[derive(Debug)]
16pub struct ApiError {
17 pub error_type: ApiErrorType,
18 pub headers: HashMap<String, String>,
19}
20impl ApiError {
21 pub fn new(error_type: ApiErrorType, headers: HashMap<String, String>) -> Self {
22 Self {
23 error_type,
24 headers,
25 }
26 }
27}
28impl fmt::Display for ApiError {
29 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30 let header_report: String = self
31 .headers
32 .iter()
33 .fold(String::new(), |a, (b0, b1)| format!("{a}\n{b0}:{b1}"));
34 match self.error_type {
35 ApiErrorType::FailedRequest(ref msg) => {
36 write!(f, "{header_report}\nFailed Request: {msg}")
37 }
38 ApiErrorType::BadJson(ref msg) => write!(f, "Bad JSON: {}", msg),
39
40 ApiErrorType::Status(ref status, ref reason) => {
42 write!(f, "{header_report}\nHTTP Status({status}) Reason: {reason}")
43 }
44
45 ApiErrorType::Error(ref msg) => write!(f, "{header_report}\nError: {msg}"),
47 }
48 }
49}
50
51impl Error for ApiError {
52 fn source(&self) -> Option<&(dyn Error + 'static)> {
53 None
54 }
55}