use std::fmt;
use serde_json::Value;
#[derive(Debug)]
pub enum Error {
BadRequest(ApiError),
Authentication(ApiError),
NotFound(ApiError),
RateLimit(ApiError),
Api(ApiError),
Transport(reqwest::Error),
}
#[derive(Debug, Clone, PartialEq)]
pub struct ApiError {
pub status: u16,
pub code: String,
pub message: String,
pub body: Option<Value>,
}
impl Error {
pub fn api(&self) -> Option<&ApiError> {
match self {
Error::BadRequest(e)
| Error::Authentication(e)
| Error::NotFound(e)
| Error::RateLimit(e)
| Error::Api(e) => Some(e),
Error::Transport(_) => None,
}
}
pub fn status(&self) -> Option<u16> {
self.api().map(|e| e.status)
}
pub fn code(&self) -> Option<&str> {
self.api()
.map(|e| e.code.as_str())
.filter(|c| !c.is_empty())
}
pub(crate) fn from_status(status: u16, body: Option<Value>) -> Self {
let field = |name: &str| {
body.as_ref()
.and_then(|b| b.get(name))
.and_then(Value::as_str)
.unwrap_or_default()
.to_string()
};
let message = match field("error") {
m if m.is_empty() => format!("HTTP {status}"),
m => m,
};
let api = ApiError {
status,
code: field("error_code"),
message,
body,
};
match status {
400 => Error::BadRequest(api),
401 => Error::Authentication(api),
404 => Error::NotFound(api),
429 => Error::RateLimit(api),
_ => Error::Api(api),
}
}
pub(crate) fn unreadable(status: u16, message: &str) -> Self {
Error::Api(ApiError {
status,
code: String::new(),
message: message.to_string(),
body: None,
})
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Transport(e) => write!(f, "ibanchecker: request failed: {e}"),
_ => {
let api = self
.api()
.expect("every non-transport variant carries an ApiError");
write!(f, "ibanchecker: {} (HTTP {})", api.message, api.status)
}
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Transport(e) => Some(e),
_ => None,
}
}
}
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Self {
Error::Transport(e)
}
}
pub type Result<T> = std::result::Result<T, Error>;