use std::fmt;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ServiceErrorKind {
MessageNotDownloadable,
DeliveryInProgress,
Other,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ServiceError {
code: String,
message: String,
reference_number: Option<String>,
}
impl ServiceError {
pub(crate) fn new(
code: impl Into<String>,
message: impl Into<String>,
reference_number: Option<String>,
) -> Self {
Self {
code: code.into(),
message: message.into(),
reference_number,
}
}
pub fn code(&self) -> &str {
&self.code
}
pub fn kind(&self) -> ServiceErrorKind {
match self.code.as_str() {
"1222" => ServiceErrorKind::MessageNotDownloadable,
"3006" => ServiceErrorKind::DeliveryInProgress,
_ => ServiceErrorKind::Other,
}
}
pub fn message(&self) -> &str {
&self.message
}
pub fn reference_number(&self) -> Option<&str> {
self.reference_number.as_deref()
}
}
impl fmt::Display for ServiceError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "ISDS status {}: {}", self.code, self.message)
}
}
impl std::error::Error for ServiceError {}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("invalid input for {field}: {message}")]
InvalidInput {
field: &'static str,
message: String,
},
#[error("HTTP transport failed: {0}")]
Transport(#[from] reqwest::Error),
#[error("ISDS authentication failed with HTTP status {status}")]
Authentication {
status: u16,
},
#[error("ISDS returned HTTP status {status}")]
Http {
status: u16,
},
#[error("SOAP fault {code}: {message}")]
SoapFault {
code: String,
message: String,
},
#[error("{0}")]
Service(#[from] ServiceError),
#[error("ISDS response exceeded the configured {limit}-byte limit")]
ResponseTooLarge {
limit: usize,
},
#[error("invalid ISDS response: {message}")]
InvalidResponse {
message: String,
},
}
impl Error {
pub(crate) fn invalid_input(field: &'static str, message: impl Into<String>) -> Self {
Self::InvalidInput {
field,
message: message.into(),
}
}
pub(crate) fn invalid_response(message: impl Into<String>) -> Self {
Self::InvalidResponse {
message: message.into(),
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn service_error_classification_preserves_the_raw_code() {
let cases = [
("1222", ServiceErrorKind::MessageNotDownloadable),
("3006", ServiceErrorKind::DeliveryInProgress),
("0002", ServiceErrorKind::Other),
("future-status", ServiceErrorKind::Other),
];
for (code, kind) in cases {
let error = ServiceError::new(code, "test status", Some("reference".to_owned()));
assert_eq!(error.kind(), kind);
assert_eq!(error.code(), code);
assert_eq!(error.message(), "test status");
assert_eq!(error.reference_number(), Some("reference"));
}
}
}