1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// SPDX-FileCopyrightText: © 2022 Svix Authors
// SPDX-License-Identifier: MIT

use std::error;
use std::fmt;

use http::status;

pub type Result<T> = std::result::Result<T, Error>;

/// The error type returned from the Svix API
#[derive(Debug, Clone)]
pub enum Error {
    /// A generic error
    Generic(String),
    /// Http Error
    Http(HttpErrorContent<crate::models::HttpErrorOut>),
    /// Http Validation Error
    Validation(HttpErrorContent<crate::models::HttpValidationError>),
}

#[derive(Debug, Clone)]
pub struct HttpErrorContent<T> {
    pub status: reqwest::StatusCode,
    pub payload: Option<T>,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::Generic(s) => s.fmt(f),
            Error::Http(e) => format!("Http error (status={}) {:?}", e.status, e.payload).fmt(f),
            Error::Validation(e) => format!("Varidation error {:?}", e.payload).fmt(f),
        }
    }
}

impl From<Error> for String {
    fn from(err: Error) -> String {
        err.to_string()
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        None
    }
}

impl<T> From<crate::apis::Error<T>> for Error {
    fn from(err: crate::apis::Error<T>) -> Error {
        match err {
            crate::apis::Error::ResponseError(e) => {
                if e.status == status::StatusCode::UNPROCESSABLE_ENTITY {
                    Error::Validation(HttpErrorContent {
                        status: e.status,
                        payload: serde_json::from_str(&e.content).ok(),
                    })
                } else {
                    Error::Http(HttpErrorContent {
                        status: e.status,
                        payload: serde_json::from_str(&e.content).ok(),
                    })
                }
            }
            _ => Error::Generic(err.to_string()),
        }
    }
}