use std::{borrow::Cow, fmt};
use bytes::Bytes;
use http::{HeaderMap, StatusCode};
use crate::request::Failure;
pub use crate::api::middleware::BoxError;
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Api(Box<ApiError>),
Timeout,
Connection(BoxError),
Decode(BoxError),
Request(BoxError),
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ApiError {
pub status: StatusCode,
pub headers: HeaderMap,
pub body: Bytes,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ApiErrorKind {
BadRequest,
Unauthorized,
PermissionDenied,
NotFound,
Conflict,
UnprocessableEntity,
RateLimited,
InternalServer,
Other,
}
impl ApiError {
#[must_use]
pub fn kind(&self) -> ApiErrorKind {
match self.status.as_u16() {
400 => ApiErrorKind::BadRequest,
401 => ApiErrorKind::Unauthorized,
403 => ApiErrorKind::PermissionDenied,
404 => ApiErrorKind::NotFound,
409 => ApiErrorKind::Conflict,
422 => ApiErrorKind::UnprocessableEntity,
429 => ApiErrorKind::RateLimited,
500..=599 => ApiErrorKind::InternalServer,
_ => ApiErrorKind::Other,
}
}
#[must_use]
pub fn text(&self) -> Cow<'_, str> {
String::from_utf8_lossy(&self.body)
}
pub fn json<T: serde::de::DeserializeOwned>(&self) -> serde_json::Result<T> {
serde_json::from_slice(&self.body)
}
#[must_use]
pub fn payload(&self) -> Option<crate::api::ErrorBody> {
self.json().ok()
}
#[must_use]
pub fn request_id(&self) -> Option<&str> {
["x-request-id", "request-id"]
.iter()
.find_map(|name| self.headers.get(*name)?.to_str().ok())
}
}
impl Error {
pub(crate) fn generic(failure: Failure) -> Self {
match failure {
Failure::Timeout => Self::Timeout,
Failure::Transport(error) => Self::Connection(error),
Failure::Decode(error) => Self::Decode(error),
Failure::Request(error) => Self::Request(error),
}
}
pub(crate) fn from_response(status: StatusCode, headers: HeaderMap, body: Bytes) -> Self {
Self::Api(Box::new(ApiError {
status,
headers,
body,
}))
}
#[must_use]
pub fn is_timeout(&self) -> bool {
matches!(self, Self::Timeout)
}
#[must_use]
pub fn is_connection(&self) -> bool {
matches!(self, Self::Connection(_))
}
#[must_use]
pub fn status(&self) -> Option<StatusCode> {
self.api().map(|error| error.status)
}
#[must_use]
pub fn kind(&self) -> Option<ApiErrorKind> {
self.api().map(ApiError::kind)
}
#[must_use]
pub fn api(&self) -> Option<&ApiError> {
match self {
Self::Api(error) => Some(error),
_ => None,
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Api(error) => write!(f, "API error ({}): {}", error.status, error.text()),
Self::Timeout => f.write_str("request timed out"),
Self::Connection(error) => write!(f, "connection error: {error}"),
Self::Decode(error) => write!(f, "unexpected response body: {error}"),
Self::Request(error) => write!(f, "invalid request: {error}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Connection(error) | Self::Decode(error) | Self::Request(error) => Some(&**error),
Self::Api(_) | Self::Timeout => None,
}
}
}