1use std::convert::Infallible;
2
3#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
5#[error("invalid {field}: {problem}")]
6pub struct ValidationError {
7 field: &'static str,
8 problem: &'static str,
9}
10
11impl ValidationError {
12 pub(crate) const fn new(field: &'static str, problem: &'static str) -> Self {
13 Self { field, problem }
14 }
15
16 #[must_use]
18 pub const fn field(&self) -> &'static str {
19 self.field
20 }
21
22 #[must_use]
24 pub const fn problem(&self) -> &'static str {
25 self.problem
26 }
27}
28
29impl From<Infallible> for ValidationError {
30 fn from(value: Infallible) -> Self {
31 match value {}
32 }
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum BusinessErrorKind {
39 InvalidRequest,
40 Authentication,
41 PermissionDenied,
42 TargetNotFound,
43 DataNotReady,
44 UnsupportedTarget,
45 RateLimited,
46 UpstreamUnavailable,
47 Other,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
52#[error("upstream business request failed with code {code}")]
53pub struct BusinessError {
54 code: i64,
55 message: String,
56 request_id: String,
57}
58
59impl BusinessError {
60 pub(crate) fn new(code: i64, message: String, request_id: String) -> Self {
61 Self {
62 code,
63 message,
64 request_id,
65 }
66 }
67
68 #[must_use]
70 pub const fn code(&self) -> i64 {
71 self.code
72 }
73
74 #[must_use]
76 pub fn message(&self) -> &str {
77 &self.message
78 }
79
80 #[must_use]
82 pub fn request_id(&self) -> &str {
83 &self.request_id
84 }
85
86 #[must_use]
88 pub const fn kind(&self) -> BusinessErrorKind {
89 match self.code {
90 1001..=1004 => BusinessErrorKind::InvalidRequest,
91 2001 | 2002 | 2004 => BusinessErrorKind::Authentication,
92 2003 => BusinessErrorKind::PermissionDenied,
93 3001 => BusinessErrorKind::TargetNotFound,
94 3002 | 4040 => BusinessErrorKind::DataNotReady,
95 3004 => BusinessErrorKind::UnsupportedTarget,
96 4001 => BusinessErrorKind::RateLimited,
97 5001..=5003 => BusinessErrorKind::UpstreamUnavailable,
98 _ => BusinessErrorKind::Other,
99 }
100 }
101}
102
103#[derive(Debug, thiserror::Error)]
105#[non_exhaustive]
106pub enum Error {
107 #[error(transparent)]
108 InvalidInput(#[from] ValidationError),
109
110 #[error("invalid client configuration")]
111 InvalidConfiguration {
112 #[source]
113 source: reqwest::Error,
114 },
115
116 #[error("HTTP transport failed")]
117 Transport {
118 #[source]
119 source: reqwest::Error,
120 },
121
122 #[error("unexpected HTTP status {status}")]
123 HttpStatus { status: u16 },
124
125 #[error("response did not match the API envelope")]
126 InvalidResponse {
127 #[source]
128 source: serde_json::Error,
129 },
130
131 #[error(transparent)]
132 Business(#[from] BusinessError),
133
134 #[error("environment variable HITHINK_FINANCE_API_KEY is not configured")]
135 MissingApiKey,
136}