use serde::Deserialize;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("{0}")]
Api(Box<ApiError>),
#[error("transport error: {0}")]
Transport(#[source] TransportError),
#[error("could not read response body: {0}")]
Read(#[source] std::io::Error),
#[error("response body larger than the limit of {limit} bytes")]
ResponseTooLarge { limit: u64 },
#[error("could not decode response: {source}")]
Decode {
#[source]
source: serde_json::Error,
body: String,
},
#[error("invalid base URL: {0}")]
InvalidBaseUrl(String),
#[error("unexpected redirect (HTTP {status}) to {}", .location.as_deref().unwrap_or("<no location>"))]
Redirect { status: u16, location: Option<String> },
#[error("invalid token: contains characters not allowed in an HTTP header")]
InvalidToken,
#[error("invalid path (empty, `.` or `..` segment): {0}")]
InvalidPath(String),
}
const BODY_PREVIEW: usize = 300;
struct Preview<'a>(&'a [u8]);
impl std::fmt::Debug for Preview<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let text = String::from_utf8_lossy(&self.0[..self.0.len().min(BODY_PREVIEW)]);
if self.0.len() > BODY_PREVIEW {
write!(f, "{text:?}… ({} bytes)", self.0.len())
} else {
write!(f, "{text:?}")
}
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Api(api) => f.debug_tuple("Api").field(api).finish(),
Self::Transport(err) => f.debug_tuple("Transport").field(err).finish(),
Self::Decode { source, body } => f
.debug_struct("Decode")
.field("source", source)
.field("body", &Preview(body.as_bytes()))
.finish(),
Self::Read(err) => f.debug_tuple("Read").field(err).finish(),
Self::ResponseTooLarge { limit } => f.debug_struct("ResponseTooLarge").field("limit", limit).finish(),
Self::InvalidBaseUrl(url) => f.debug_tuple("InvalidBaseUrl").field(url).finish(),
Self::Redirect { status, location } => f
.debug_struct("Redirect")
.field("status", status)
.field("location", location)
.finish(),
Self::InvalidToken => f.write_str("InvalidToken"),
Self::InvalidPath(path) => f.debug_tuple("InvalidPath").field(path).finish(),
}
}
}
impl Error {
pub fn api(&self) -> Option<&ApiError> {
match self {
Self::Api(api) => Some(api),
_ => None,
}
}
pub fn status(&self) -> Option<u16> {
match self {
Self::Api(api) => Some(api.status),
Self::Redirect { status, .. } => Some(*status),
_ => None,
}
}
pub fn is_not_found(&self) -> bool {
self.status() == Some(404)
}
pub fn is_unauthorized(&self) -> bool {
self.status() == Some(401)
}
pub fn is_forbidden(&self) -> bool {
self.status() == Some(403)
}
pub fn is_timeout(&self) -> bool {
matches!(self, Self::Transport(e) if e.is_timeout())
}
pub fn is_connect(&self) -> bool {
matches!(self, Self::Transport(e) if e.is_connect())
}
}
impl From<ApiError> for Error {
fn from(err: ApiError) -> Self {
Self::Api(Box::new(err))
}
}
impl Error {
pub(crate) fn transport(err: reqwest::Error) -> Self {
Self::Transport(TransportError(err))
}
}
pub struct TransportError(reqwest::Error);
impl TransportError {
pub fn is_timeout(&self) -> bool {
self.0.is_timeout()
}
pub fn is_connect(&self) -> bool {
self.0.is_connect()
}
}
impl std::fmt::Display for TransportError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::fmt::Debug for TransportError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for TransportError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.0.source()
}
}
#[derive(Clone, thiserror::Error)]
#[error("HTTP {status}: {}", .message.as_deref().unwrap_or("<no message>"))]
pub struct ApiError {
pub status: u16,
pub message: Option<String>,
pub translated_message: Option<String>,
pub message_key: Option<String>,
pub args: serde_json::Value,
pub errors: serde_json::Value,
pub body: Vec<u8>,
}
impl std::fmt::Debug for ApiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ApiError")
.field("status", &self.status)
.field("message", &self.message)
.field("translated_message", &self.translated_message)
.field("message_key", &self.message_key)
.field("args", &self.args)
.field("errors", &self.errors)
.field("body", &Preview(&self.body))
.finish()
}
}
#[derive(Deserialize, Default)]
#[serde(rename_all = "camelCase", default)]
struct ErrorBody {
message: Option<String>,
translated_message: Option<String>,
message_key: Option<String>,
args: serde_json::Value,
errors: serde_json::Value,
}
impl ApiError {
pub fn from_response(status: u16, body: Vec<u8>) -> Self {
let parsed: ErrorBody = serde_json::from_slice(&body).unwrap_or_default();
Self {
status,
message: parsed.message,
translated_message: parsed.translated_message,
message_key: parsed.message_key,
args: parsed.args,
errors: parsed.errors,
body,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn helpers_classify_errors() {
let not_found = Error::from(ApiError::from_response(404, br#"{"message":"nope"}"#.to_vec()));
assert!(not_found.is_not_found() && !not_found.is_forbidden());
assert_eq!(not_found.api().and_then(|a| a.message.as_deref()), Some("nope"));
let redirect = Error::Redirect { status: 302, location: None };
assert_eq!((redirect.status(), redirect.api().is_none()), (Some(302), true));
assert_eq!(Error::InvalidToken.status(), None);
}
#[test]
fn debug_shortens_long_bodies() {
let body = format!(r#"{{"data":[{}]}}"#, r#"{"email":"anna@example.org"},"#.repeat(100));
let err = crate::decode::<i64>(body.as_bytes()).unwrap_err();
let debug = format!("{err:?}");
assert!(debug.len() < 1000, "{debug}");
assert!(debug.contains(&format!("({} bytes)", body.len())));
let Error::Decode { body: full, .. } = &err else { panic!() };
assert_eq!(full.len(), body.len());
let api = ApiError::from_response(500, body.into_bytes());
assert!(format!("{api:?}").len() < 1000);
let short = ApiError::from_response(404, br#"{"message":"nope"}"#.to_vec());
assert!(format!("{short:?}").contains(r#"body: "{\"message\":\"nope\"}""#));
}
}