use std::fmt;
use alloy::signers::Error as SignerError;
#[derive(Debug)]
pub enum Error {
Network(reqwest::Error),
Api(String),
Json(serde_json::Error),
Signing(SignerError),
InvalidOrder {
message: String,
},
WebSocket(String),
InvalidAddress(String),
Timeout,
Other(String),
}
impl Error {
#[must_use]
pub fn is_retryable(&self) -> bool {
matches!(
self,
Error::Network(_) | Error::Timeout | Error::WebSocket(_)
)
}
#[must_use]
pub fn is_network_error(&self) -> bool {
matches!(self, Error::Network(_) | Error::Timeout)
}
#[must_use]
pub fn is_api_error(&self) -> bool {
matches!(self, Error::Api(_))
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Network(e) => write!(f, "Network error: {}", e),
Error::Api(e) => write!(f, "API error: {}", e),
Error::Json(e) => write!(f, "JSON error: {}", e),
Error::Signing(e) => write!(f, "Signing error: {}", e),
Error::InvalidOrder { message } => write!(f, "Invalid order: {}", message),
Error::WebSocket(e) => write!(f, "WebSocket error: {}", e),
Error::InvalidAddress(e) => write!(f, "Invalid address: {}", e),
Error::Timeout => write!(f, "Operation timed out"),
Error::Other(e) => write!(f, "{}", e),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Network(e) => Some(e),
Error::Json(e) => Some(e),
Error::Signing(e) => Some(e),
_ => None,
}
}
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Self {
if e.is_timeout() {
Error::Timeout
} else {
Error::Network(e)
}
}
}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Self {
Error::Json(e)
}
}
impl From<SignerError> for Error {
fn from(e: SignerError) -> Self {
Error::Signing(e)
}
}
impl From<url::ParseError> for Error {
fn from(e: url::ParseError) -> Self {
Error::Other(format!("URL parse error: {}", e))
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Error::Other(format!("IO error: {}", e))
}
}
impl From<anyhow::Error> for Error {
fn from(e: anyhow::Error) -> Self {
Error::Other(e.to_string())
}
}
#[derive(Debug, Clone)]
pub struct ActionError<T> {
pub(crate) ids: Vec<T>,
pub(crate) err: String,
}
impl<T> ActionError<T> {
pub fn new(ids: Vec<T>, err: String) -> Self {
Self { ids, err }
}
pub fn message(&self) -> &str {
&self.err
}
pub fn ids(&self) -> &[T] {
&self.ids
}
pub fn into_ids(self) -> Vec<T> {
self.ids
}
}
impl<T> fmt::Display for ActionError<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}, ids: {:?}", self.err, self.ids)
}
}
impl<T> std::error::Error for ActionError<T> where T: fmt::Display + fmt::Debug {}