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
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
use http;
use serde_json;
use serde_qs;
//use crate::util::to_snakecase;
use reqwest;
use std::error::Error as StdError;
use std::fmt;
use std::io;

macro_rules! from_error {
    ($f: ty, $e: expr) => {
        impl From<$f> for Error {
            fn from(f: $f) -> Error {
                $e(f)
            }
        }
    };
}
#[derive(Debug)]
pub enum Error {
    Stripe(StripeErrorObject),
    Http(reqwest::Error),
    Json(serde_json::error::Error),
    Uri(http::uri::InvalidUri),
    Io(io::Error),
    QsError(serde_qs::Error),
    HeaderError(reqwest::header::InvalidHeaderValue),
    Unknown,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::Stripe(ref err) => write!(f, ": {:?}", err),
            Error::Http(ref err) => write!(f, ": {}", err),
            Error::Json(ref err) => write!(f, ": {}", err),
            Error::Uri(ref err) => write!(f, ": {}", err),
            Error::Io(ref err) => write!(f, ": {}", err),
            Error::QsError(ref err) => write!(f, ": {}", err),
            Error::HeaderError(ref err) => write!(f, ": {}", err),
            Error::Unknown => write!(f, ": unknown error"),
        }
    }
}

from_error!(StripeErrorObject, Error::Stripe);
from_error!(reqwest::Error, Error::Http);
from_error!(reqwest::header::InvalidHeaderValue, Error::HeaderError);
from_error!(serde_json::Error, Error::Json);
from_error!(http::uri::InvalidUri, Error::Uri);
from_error!(io::Error, Error::Io);
from_error!(serde_qs::Error, Error::QsError);

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match *self {
            Error::Http(ref err) => Some(err),
            Error::Json(ref err) => Some(err),
            Error::Uri(ref err) => Some(err),
            Error::Io(ref err) => Some(err),
            Error::HeaderError(ref err) => Some(err),
            Error::QsError(ref err) => Some(err),
            _ => None,
        }
    }
}

#[derive(Debug, PartialEq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorType {
    ApiError,
    ApiConnectionError,
    AuthenticationError,
    CardError,
    InvalidRequestError,
    RateLimitError,
    ValidationError,
    #[serde(skip_deserializing)]
    Unknown,
}

impl Default for ErrorType {
    fn default() -> Self {
        ErrorType::Unknown
    }
}

impl fmt::Display for ErrorType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq, Hash)]
#[serde(rename_all = "snake_case")]
pub enum ErrorCode {
    InvalidNumber,
    InvalidExpiryMonth,
    InvalidExpiryYear,
    InvalidCvc,
    InvalidSwipeData,
    IncorrectNumber,
    ExpiredCard,
    IncorrectCvc,
    IncorrectZip,
    CardDeclined,
    Missing,
    ProcessingError,
    ParameterMissing,
    AccountAlreadyExists,
    AccountCountryInvalidAddress,
    AccountInvalid,
    AccountNumberInvalid,
    AlipayUpgradeRequired,
    AmountTooLarge,
    AmountTooSmall,
    ApiKeyExpired,
    BalanceInsufficient,
    BankAccountExists,
    BankAccountUnusable,
    BankAccountUnverified,
    ChargeAlreadyCaptured,
    ChargeAlreadyRefunded,
    ChargeExpiredForCapture,
    CountryUnsupported,
    CouponExpired,
    CustomerMaxSubscriptions,
    EmailInvalid,
    InstantPayoutsUnsupported,
    InvalidCardType,
    InvalidChargeAmount,
    InvalidSourceUsage,
    InvoiceNoCustomerLineItems,
    InvoiceNoSubscriptionLineItems,
    InvoiceNotEditable,
    InvoiceUpcomingNone,
    LivemodeMismatch,
    OrderCreationFailed,
    OrderRequiredSettings,
    OrderStatusInvalid,
    OrderUpstreamTimeout,
    OutOfInventory,
    ParameterInvalidEmpty,
    ParameterInvalidInteger,
    ParameterInvalidStringBlank,
    ParameterInvalidStringEmpty,
    ParameterUnknown,
    PaymentMethodUnactivated,
    PayoutNotAllowed,
    PlatformApiKeyExpired,
    PostalCodeInvalid,
    ProductInactive,
    RateLimit,
    ResourceAlreadyExists,
    ResourceMissing,
    RoutingNumberInvalid,
    SecretKeyRequired,
    SepaUnsupportedAccount,
    ShippingCalculationFailed,
    SkuInactive,
    StateUnsupported,
    TaxIdInvalid,
    TaxesCalculationFailed,
    TestmodeChargesOnly,
    TlsVersionUnsupported,
    TokenAlreadyUsed,
    TokenInUse,
    TransfersNotAllowed,
    UrlInvalid,
    InvalidUtf8InPostBody,
}

impl fmt::Display for ErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

#[derive(Debug, Default, Deserialize)]
pub struct StripeErrorObject {
    pub error: StripeRequestObject,
}

#[derive(Debug, Default, Deserialize)]
pub struct StripeRequestObject {
    #[serde(rename = "type")]
    pub error_type: ErrorType,
    pub charge: Option<String>,
    #[serde(default)]
    pub message: Option<String>,
    pub code: Option<ErrorCode>,
    pub decline_code: Option<String>,
    pub param: Option<String>,
    pub doc_url: Option<String>,
}

impl fmt::Display for StripeErrorObject {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.error.error_type)?;
        if let Some(ref message) = self.error.message {
            write!(f, ": {}", message)?;
        }
        Ok(())
    }
}