oicp_kit/transport/
error.rs1use crate::types::{Acknowledgement, Code, StatusCode, Violations};
4
5#[derive(Debug, thiserror::Error)]
23#[non_exhaustive]
24pub enum OicpError {
25 #[error("the request to Hubject failed: {message}")]
27 Transport {
28 message: String,
30 #[source]
32 source: Option<Box<dyn std::error::Error + Send + Sync>>,
33 },
34
35 #[error("{url} answered {status}{}{}", body_excerpt(.body), path_hint(*.status, .url))]
41 Http {
42 status: u16,
44 url: String,
46 body: String,
48 },
49
50 #[error("Hubject rejected the operation: {status_code}")]
55 Rejected {
56 status_code: StatusCode,
58 acknowledgement: Box<Acknowledgement>,
60 },
61
62 #[error("could not decode Hubject's answer{}: {message}", pointer_suffix(.pointer.as_deref()))]
64 Decode {
65 message: String,
67 pointer: Option<String>,
69 },
70
71 #[error("the request is not conformant: {0}")]
76 Invalid(#[from] Violations),
77
78 #[error(transparent)]
80 Endpoint(#[from] super::endpoint::EndpointError),
81}
82
83fn body_excerpt(body: &str) -> String {
84 if body.is_empty() {
85 String::new()
86 } else {
87 let trimmed: String = body.chars().take(200).collect();
88 format!(": {trimmed}")
89 }
90}
91
92fn pointer_suffix(pointer: Option<&str>) -> String {
93 pointer.map_or_else(String::new, |p| format!(" at {p}"))
94}
95
96fn path_hint(status: u16, url: &str) -> &'static str {
99 if status == 404 && !url.contains("/api/oicp") {
100 ". Every OICP endpoint hangs off `…/api/oicp`; a base URL without that path 404s on every call"
101 } else {
102 ""
103 }
104}
105
106impl OicpError {
107 pub fn transport(message: impl Into<String>) -> Self {
109 Self::Transport { message: message.into(), source: None }
110 }
111
112 pub fn transport_from(
114 message: impl Into<String>,
115 source: impl std::error::Error + Send + Sync + 'static,
116 ) -> Self {
117 Self::Transport { message: message.into(), source: Some(Box::new(source)) }
118 }
119
120 #[must_use]
122 pub fn rejected(acknowledgement: Acknowledgement) -> Self {
123 Self::Rejected {
124 status_code: acknowledgement.status_code.clone(),
125 acknowledgement: Box::new(acknowledgement),
126 }
127 }
128
129 #[must_use]
131 pub fn code(&self) -> Option<&Code> {
132 match self {
133 Self::Rejected { status_code, .. } => Some(&status_code.code),
134 _ => None,
135 }
136 }
137
138 #[must_use]
147 pub fn is_retryable(&self) -> bool {
148 match self {
149 Self::Transport { .. } => true,
150 Self::Http { status, .. } => *status >= 500 || *status == 429,
151 Self::Rejected { status_code, .. } => status_code.code.is_retryable(),
152 Self::Decode { .. } | Self::Invalid(_) | Self::Endpoint(_) => false,
153 }
154 }
155
156 #[must_use]
158 pub fn is_authorization_failure(&self) -> bool {
159 self.code().is_some_and(Code::is_authorization_failure)
160 }
161}
162
163pub type Result<T> = core::result::Result<T, OicpError>;
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169
170 #[test]
171 fn a_two_hundred_with_result_false_is_an_error() {
172 let ack = Acknowledgement::failure(Code::UnknownEvseId);
173 let err = OicpError::rejected(ack);
174 assert_eq!(err.code(), Some(&Code::UnknownEvseId));
175 assert!(!err.is_retryable());
176 assert!(err.to_string().contains("603"));
177 }
178
179 #[test]
180 fn retryability_follows_the_layer_the_failure_came_from() {
181 assert!(OicpError::transport("connection reset").is_retryable());
182 let http = |status| OicpError::Http { status, url: "https://x/api/oicp".into(), body: String::new() };
183 assert!(http(503).is_retryable());
184 assert!(http(429).is_retryable());
185 assert!(!http(400).is_retryable());
186 assert!(!OicpError::Decode { message: "bad".into(), pointer: None }.is_retryable());
187
188 assert!(OicpError::rejected(Acknowledgement::failure(Code::ServiceNotAvailable)).is_retryable());
190 assert!(!OicpError::rejected(Acknowledgement::failure(Code::NoValidContract)).is_retryable());
191 }
192
193 #[test]
194 fn an_authorization_failure_is_distinguishable_from_a_breakage() {
195 let refused = OicpError::rejected(Acknowledgement::failure(Code::EvcoIdLocked));
196 assert!(refused.is_authorization_failure());
197 let broken = OicpError::rejected(Acknowledgement::failure(Code::HubjectSystemError));
198 assert!(!broken.is_authorization_failure());
199 }
200
201 #[test]
202 fn a_long_error_body_is_truncated_in_the_message() {
203 let err = OicpError::Http { status: 500, url: "https://x/api/oicp".into(), body: "x".repeat(1000) };
204 assert!(err.to_string().len() < 320, "{err}");
205 }
206
207 #[test]
208 fn a_404_on_a_base_url_without_its_path_says_so() {
209 let missing = OicpError::Http {
212 status: 404,
213 url: "http://127.0.0.1:8080/evsepull/v23/providers/DE-DCB/data-records".into(),
214 body: String::new(),
215 };
216 assert!(missing.to_string().contains("/api/oicp"), "{missing}");
217
218 let genuine = OicpError::Http {
219 status: 404,
220 url: "https://service.hubject.com/api/oicp/evsepull/v23/x".into(),
221 body: String::new(),
222 };
223 assert!(!genuine.to_string().contains("hangs off"), "{genuine}");
224
225 let server = OicpError::Http { status: 500, url: "http://x/y".into(), body: String::new() };
227 assert!(!server.to_string().contains("hangs off"), "{server}");
228 }
229}