use crate::types::{Acknowledgement, Code, StatusCode, Violations};
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum OicpError {
#[error("the request to Hubject failed: {message}")]
Transport {
message: String,
#[source]
source: Option<Box<dyn std::error::Error + Send + Sync>>,
},
#[error("{url} answered {status}{}{}", body_excerpt(.body), path_hint(*.status, .url))]
Http {
status: u16,
url: String,
body: String,
},
#[error("Hubject rejected the operation: {status_code}")]
Rejected {
status_code: StatusCode,
acknowledgement: Box<Acknowledgement>,
},
#[error("could not decode Hubject's answer{}: {message}", pointer_suffix(.pointer.as_deref()))]
Decode {
message: String,
pointer: Option<String>,
},
#[error("the request is not conformant: {0}")]
Invalid(#[from] Violations),
#[error(transparent)]
Endpoint(#[from] super::endpoint::EndpointError),
}
fn body_excerpt(body: &str) -> String {
if body.is_empty() {
String::new()
} else {
let trimmed: String = body.chars().take(200).collect();
format!(": {trimmed}")
}
}
fn pointer_suffix(pointer: Option<&str>) -> String {
pointer.map_or_else(String::new, |p| format!(" at {p}"))
}
fn path_hint(status: u16, url: &str) -> &'static str {
if status == 404 && !url.contains("/api/oicp") {
". Every OICP endpoint hangs off `…/api/oicp`; a base URL without that path 404s on every call"
} else {
""
}
}
impl OicpError {
pub fn transport(message: impl Into<String>) -> Self {
Self::Transport { message: message.into(), source: None }
}
pub fn transport_from(
message: impl Into<String>,
source: impl std::error::Error + Send + Sync + 'static,
) -> Self {
Self::Transport { message: message.into(), source: Some(Box::new(source)) }
}
#[must_use]
pub fn rejected(acknowledgement: Acknowledgement) -> Self {
Self::Rejected {
status_code: acknowledgement.status_code.clone(),
acknowledgement: Box::new(acknowledgement),
}
}
#[must_use]
pub fn code(&self) -> Option<&Code> {
match self {
Self::Rejected { status_code, .. } => Some(&status_code.code),
_ => None,
}
}
#[must_use]
pub fn is_retryable(&self) -> bool {
match self {
Self::Transport { .. } => true,
Self::Http { status, .. } => *status >= 500 || *status == 429,
Self::Rejected { status_code, .. } => status_code.code.is_retryable(),
Self::Decode { .. } | Self::Invalid(_) | Self::Endpoint(_) => false,
}
}
#[must_use]
pub fn is_authorization_failure(&self) -> bool {
self.code().is_some_and(Code::is_authorization_failure)
}
}
pub type Result<T> = core::result::Result<T, OicpError>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_two_hundred_with_result_false_is_an_error() {
let ack = Acknowledgement::failure(Code::UnknownEvseId);
let err = OicpError::rejected(ack);
assert_eq!(err.code(), Some(&Code::UnknownEvseId));
assert!(!err.is_retryable());
assert!(err.to_string().contains("603"));
}
#[test]
fn retryability_follows_the_layer_the_failure_came_from() {
assert!(OicpError::transport("connection reset").is_retryable());
let http = |status| OicpError::Http { status, url: "https://x/api/oicp".into(), body: String::new() };
assert!(http(503).is_retryable());
assert!(http(429).is_retryable());
assert!(!http(400).is_retryable());
assert!(!OicpError::Decode { message: "bad".into(), pointer: None }.is_retryable());
assert!(OicpError::rejected(Acknowledgement::failure(Code::ServiceNotAvailable)).is_retryable());
assert!(!OicpError::rejected(Acknowledgement::failure(Code::NoValidContract)).is_retryable());
}
#[test]
fn an_authorization_failure_is_distinguishable_from_a_breakage() {
let refused = OicpError::rejected(Acknowledgement::failure(Code::EvcoIdLocked));
assert!(refused.is_authorization_failure());
let broken = OicpError::rejected(Acknowledgement::failure(Code::HubjectSystemError));
assert!(!broken.is_authorization_failure());
}
#[test]
fn a_long_error_body_is_truncated_in_the_message() {
let err = OicpError::Http { status: 500, url: "https://x/api/oicp".into(), body: "x".repeat(1000) };
assert!(err.to_string().len() < 320, "{err}");
}
#[test]
fn a_404_on_a_base_url_without_its_path_says_so() {
let missing = OicpError::Http {
status: 404,
url: "http://127.0.0.1:8080/evsepull/v23/providers/DE-DCB/data-records".into(),
body: String::new(),
};
assert!(missing.to_string().contains("/api/oicp"), "{missing}");
let genuine = OicpError::Http {
status: 404,
url: "https://service.hubject.com/api/oicp/evsepull/v23/x".into(),
body: String::new(),
};
assert!(!genuine.to_string().contains("hangs off"), "{genuine}");
let server = OicpError::Http { status: 500, url: "http://x/y".into(), body: String::new() };
assert!(!server.to_string().contains("hangs off"), "{server}");
}
}