use std::fmt;
use crate::api::ApiResponse;
use crate::schema::{
AnyResponse, CreateTransactionResponse, Message, Messages, TransactionResponse,
};
use crate::validate::ValidationError;
use crate::xml::XmlError;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Api(Box<ApiError>),
#[error("invalid request: {0}")]
Validation(#[from] ValidationError),
#[error(transparent)]
Xml(#[from] XmlError),
#[error("HTTP status {status}")]
Status {
status: u16,
body: String,
},
#[error("HTTP request failed: {0}")]
Transport(#[from] TransportError),
}
impl Error {
pub fn as_api(&self) -> Option<&ApiError> {
match self {
Error::Api(err) => Some(err),
_ => None,
}
}
}
impl From<ApiError> for Error {
fn from(err: ApiError) -> Self {
Error::Api(Box::new(err))
}
}
#[derive(Debug, thiserror::Error)]
#[error("{source}")]
pub struct TransportError {
source: Box<dyn std::error::Error + Send + Sync>,
timeout: bool,
}
impl TransportError {
pub fn new(source: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
Self {
source: source.into(),
timeout: false,
}
}
pub fn timeout(source: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
Self {
source: source.into(),
timeout: true,
}
}
pub fn is_timeout(&self) -> bool {
self.timeout
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ApiError {
messages: Messages,
response: Option<AnyResponse>,
}
impl ApiError {
pub(crate) fn new(messages: Messages, response: Option<AnyResponse>) -> Self {
Self { messages, response }
}
fn first(&self) -> Option<&Message> {
self.messages.message.first()
}
pub fn code(&self) -> &str {
self.first().map_or("", |m| m.code.as_str())
}
pub fn text(&self) -> &str {
self.first().map_or("", |m| m.text.as_str())
}
pub fn messages(&self) -> &Messages {
&self.messages
}
pub fn any_response(&self) -> Option<&AnyResponse> {
self.response.as_ref()
}
pub fn response<T: ApiResponse>(&self) -> Option<&T> {
self.response.as_ref().and_then(T::from_any)
}
pub fn transaction_response(&self) -> Option<&TransactionResponse> {
self.response::<CreateTransactionResponse>()
.map(|response| &response.transaction_response)
}
pub fn into_response(self) -> Option<AnyResponse> {
self.response
}
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[{}] {}", self.code(), self.text())
}
}
impl std::error::Error for ApiError {}