use std::{collections::BTreeMap, error::Error, fmt};
use serde_json::Value;
use crate::{
ErrorEnvelope, FailureMetadata,
redaction::{redact_json_value, redact_urls_in_text},
};
#[derive(Debug, Clone, PartialEq)]
pub struct DataError {
code: String,
message: String,
module: String,
attributes: BTreeMap<String, Value>,
failure: FailureMetadata,
}
impl DataError {
#[must_use]
pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
let message = message.into();
Self {
code: code.into(),
message: redact_urls_in_text(&message, true),
module: "dataexcept".to_owned(),
attributes: BTreeMap::new(),
failure: FailureMetadata::unknown(),
}
}
#[must_use]
pub fn with_module(mut self, module: impl Into<String>) -> Self {
self.module = module.into();
self
}
#[must_use]
pub fn with_attribute(mut self, key: impl Into<String>, value: Value) -> Self {
self.attributes
.insert(key.into(), redact_json_value(value, true));
self
}
#[must_use]
pub fn with_failure(mut self, failure: FailureMetadata) -> Self {
self.failure = failure;
self
}
#[must_use]
pub fn code(&self) -> &str {
&self.code
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
#[must_use]
pub fn module(&self) -> &str {
&self.module
}
#[must_use]
pub fn attributes(&self) -> &BTreeMap<String, Value> {
&self.attributes
}
#[must_use]
pub fn failure(&self) -> &FailureMetadata {
&self.failure
}
#[must_use]
pub fn to_envelope(&self) -> ErrorEnvelope {
ErrorEnvelope::new(&self.code, &self.module, &self.message)
.with_attributes(self.attributes.clone())
.with_failure(self.failure.clone())
}
}
impl From<&DataError> for ErrorEnvelope {
fn from(value: &DataError) -> Self {
value.to_envelope()
}
}
impl From<DataError> for ErrorEnvelope {
fn from(value: DataError) -> Self {
value.to_envelope()
}
}
impl fmt::Display for DataError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}: {}", self.code, self.message)
}
}
impl Error for DataError {}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::DataError;
use crate::FailureMetadata;
#[test]
fn exposes_structured_fields_without_serialization() {
let error = DataError::new("missing_column", "customer_id is required")
.with_module("pipeline::validation")
.with_attribute("column", json!("customer_id"))
.with_failure(FailureMetadata::permanent());
assert_eq!(error.code(), "missing_column");
assert_eq!(error.message(), "customer_id is required");
assert_eq!(error.module(), "pipeline::validation");
assert_eq!(
error.attributes().get("column"),
Some(&json!("customer_id"))
);
assert_eq!(error.failure(), &FailureMetadata::permanent());
}
#[test]
fn converts_by_reference_into_envelope() {
let error = DataError::new("missing_column", "customer_id is required");
let envelope = crate::ErrorEnvelope::from(&error);
assert_eq!(envelope.error_type, "missing_column");
assert_eq!(envelope.message, "customer_id is required");
}
#[test]
fn converts_owned_value_into_envelope() {
let error = DataError::new("missing_column", "customer_id is required");
let envelope = crate::ErrorEnvelope::from(error);
assert_eq!(envelope.error_type, "missing_column");
assert_eq!(envelope.message, "customer_id is required");
}
#[test]
fn converts_to_structured_envelope() {
let error = DataError::new("missing_column", "customer_id is required")
.with_module("pipeline::validation")
.with_attribute("column", json!("customer_id"))
.with_failure(FailureMetadata::permanent());
let envelope = error.to_envelope();
assert_eq!(envelope.error_type, "missing_column");
assert_eq!(envelope.module, "pipeline::validation");
assert_eq!(
envelope
.attributes
.expect("attributes should exist")
.get("column"),
Some(&json!("customer_id"))
);
}
#[test]
fn display_redacts_url_credentials() {
let error = DataError::new(
"request_failed",
"GET https://user:secret@example.com/v1?token=SECRETVALUE failed",
);
let rendered = error.to_string();
assert!(!rendered.contains("secret"));
assert!(!rendered.contains("SECRETVALUE"));
assert!(rendered.contains("example.com"));
assert!(rendered.contains("/v1"));
}
#[test]
fn attributes_redact_nested_url_credentials() {
let error = DataError::new("request_failed", "request failed").with_attribute(
"request",
json!({
"endpoint": "https://example.com/v1?api_key=SECRETVALUE",
}),
);
let envelope = error.to_envelope();
let attributes = envelope.attributes.expect("attributes should exist");
assert_eq!(
attributes["request"]["endpoint"],
"https://example.com/***?api_key=***"
);
}
}