use std::convert::Infallible;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("invalid {field}: {problem}")]
pub struct ValidationError {
field: &'static str,
problem: &'static str,
}
impl ValidationError {
pub(crate) const fn new(field: &'static str, problem: &'static str) -> Self {
Self { field, problem }
}
#[must_use]
pub const fn field(&self) -> &'static str {
self.field
}
#[must_use]
pub const fn problem(&self) -> &'static str {
self.problem
}
}
impl From<Infallible> for ValidationError {
fn from(value: Infallible) -> Self {
match value {}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BusinessErrorKind {
InvalidRequest,
Authentication,
PermissionDenied,
TargetNotFound,
DataNotReady,
UnsupportedTarget,
RateLimited,
UpstreamUnavailable,
Other,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("upstream business request failed with code {code}")]
pub struct BusinessError {
code: i64,
message: String,
request_id: String,
}
impl BusinessError {
pub(crate) fn new(code: i64, message: String, request_id: String) -> Self {
Self {
code,
message,
request_id,
}
}
#[must_use]
pub const fn code(&self) -> i64 {
self.code
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[must_use]
pub fn request_id(&self) -> &str {
&self.request_id
}
#[must_use]
pub const fn kind(&self) -> BusinessErrorKind {
match self.code {
1001..=1004 => BusinessErrorKind::InvalidRequest,
2001 | 2002 | 2004 => BusinessErrorKind::Authentication,
2003 => BusinessErrorKind::PermissionDenied,
3001 => BusinessErrorKind::TargetNotFound,
3002 | 4040 => BusinessErrorKind::DataNotReady,
3004 => BusinessErrorKind::UnsupportedTarget,
4001 => BusinessErrorKind::RateLimited,
5001..=5003 => BusinessErrorKind::UpstreamUnavailable,
_ => BusinessErrorKind::Other,
}
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
InvalidInput(#[from] ValidationError),
#[error("invalid client configuration")]
InvalidConfiguration {
#[source]
source: reqwest::Error,
},
#[error("HTTP transport failed")]
Transport {
#[source]
source: reqwest::Error,
},
#[error("unexpected HTTP status {status}")]
HttpStatus { status: u16 },
#[error("response did not match the API envelope")]
InvalidResponse {
#[source]
source: serde_json::Error,
},
#[error(transparent)]
Business(#[from] BusinessError),
#[error("environment variable HITHINK_FINANCE_API_KEY is not configured")]
MissingApiKey,
}