use anyhow::Error;
#[derive(Debug, Clone, Default)]
pub struct FailureContext {
pub final_url: Option<String>,
pub redirect_chain: Vec<String>,
pub response_headers: Vec<(String, String)>,
}
#[derive(Debug)]
pub struct FailureContextError {
pub context: FailureContext,
}
impl std::fmt::Display for FailureContextError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(ref final_url) = self.context.final_url {
if self.context.redirect_chain.is_empty() {
write!(f, "Request failed for {final_url}")
} else {
write!(
f,
"Request failed for {} (redirected from {} via {} hop(s))",
final_url,
self.context.redirect_chain.first().unwrap_or(final_url),
self.context.redirect_chain.len().saturating_sub(1)
)
}
} else {
write!(f, "Request failed (no final URL available)")
}
}
}
impl std::error::Error for FailureContextError {}
pub fn attach_failure_context(error: anyhow::Error, context: FailureContext) -> anyhow::Error {
let context_error = anyhow::Error::from(FailureContextError { context });
context_error.context(error)
}
pub fn extract_failure_context(error: &Error) -> FailureContext {
if let Some(context_err) = error.downcast_ref::<FailureContextError>() {
return context_err.context.clone();
}
FailureContext::default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_attach_failure_context() {
let context = FailureContext {
final_url: Some("https://example.com".to_string()),
redirect_chain: vec!["https://example.org".to_string()],
response_headers: vec![("content-type".to_string(), "text/html".to_string())],
};
let original_error = anyhow::anyhow!("HTTP request failed");
let error_with_context = attach_failure_context(original_error, context.clone());
let extracted = extract_failure_context(&error_with_context);
assert_eq!(extracted.final_url, context.final_url);
assert_eq!(extracted.redirect_chain, context.redirect_chain);
assert_eq!(extracted.response_headers, context.response_headers);
}
#[test]
fn test_attach_failure_context_preserves_original_error() {
let context = FailureContext {
final_url: Some("https://example.com".to_string()),
redirect_chain: vec![],
response_headers: vec![],
};
let original_error = anyhow::anyhow!("Connection timeout");
let error_with_context = attach_failure_context(original_error, context);
let error_msg = error_with_context.to_string();
let has_original = error_msg.contains("Connection timeout")
|| error_msg.contains("timeout")
|| error_with_context
.chain()
.any(|e| e.to_string().contains("Connection timeout"));
assert!(
has_original,
"Original error message not found in chain. Error: {}",
error_msg
);
}
#[test]
fn test_extract_failure_context_nested_chain() {
let context = FailureContext {
final_url: Some("https://example.com".to_string()),
redirect_chain: vec!["https://example.org".to_string()],
response_headers: vec![],
};
let error = attach_failure_context(
anyhow::anyhow!("Root error").context("Middle context"),
context.clone(),
)
.context("Top context");
let extracted = extract_failure_context(&error);
assert_eq!(extracted.final_url, context.final_url);
assert_eq!(extracted.redirect_chain, context.redirect_chain);
}
#[test]
fn test_extract_failure_context_empty_context() {
let error = anyhow::anyhow!("Simple error");
let extracted = extract_failure_context(&error);
assert_eq!(extracted.final_url, None);
assert_eq!(extracted.redirect_chain, Vec::<String>::new());
assert_eq!(extracted.response_headers, Vec::<(String, String)>::new());
}
#[test]
fn test_failure_context_error_display_with_redirects() {
let context = FailureContext {
final_url: Some("https://www.example.com".to_string()),
redirect_chain: vec![
"https://example.com".to_string(),
"https://www.example.com".to_string(),
],
response_headers: vec![],
};
let context_error = FailureContextError { context };
let display_msg = context_error.to_string();
assert!(display_msg.contains("www.example.com"));
assert!(display_msg.contains("hop"));
}
#[test]
fn test_failure_context_error_display_without_redirects() {
let context = FailureContext {
final_url: Some("https://example.com".to_string()),
redirect_chain: vec![],
response_headers: vec![],
};
let context_error = FailureContextError { context };
let display_msg = context_error.to_string();
assert!(display_msg.contains("example.com"));
assert!(!display_msg.contains("hop"));
}
#[test]
fn test_failure_context_error_display_no_final_url() {
let context = FailureContext {
final_url: None,
redirect_chain: vec![],
response_headers: vec![],
};
let context_error = FailureContextError { context };
let display_msg = context_error.to_string();
assert!(display_msg.contains("no final URL available"));
}
#[test]
fn test_extract_failure_context_error_chain_order() {
let context = FailureContext {
final_url: Some("https://example.com".to_string()),
redirect_chain: vec![],
response_headers: vec![],
};
let error = attach_failure_context(anyhow::anyhow!("Root error"), context.clone());
let extracted = extract_failure_context(&error);
assert_eq!(extracted.final_url, context.final_url);
}
#[test]
fn test_extract_failure_context_large_redirect_chain() {
let redirect_chain: Vec<String> = (0..100)
.map(|i| format!("https://example.com/redirect{}", i))
.collect();
let context = FailureContext {
final_url: Some("https://example.com/final".to_string()),
redirect_chain: redirect_chain.clone(),
response_headers: vec![],
};
let error = attach_failure_context(anyhow::anyhow!("Test error"), context.clone());
let extracted = extract_failure_context(&error);
assert_eq!(extracted.redirect_chain.len(), redirect_chain.len());
assert_eq!(extracted.redirect_chain, redirect_chain);
}
#[test]
fn test_extract_failure_context_many_headers() {
let response_headers: Vec<(String, String)> = (0..50)
.map(|i| (format!("header-{}", i), format!("value-{}", i)))
.collect();
let context = FailureContext {
final_url: Some("https://example.com".to_string()),
redirect_chain: vec![],
response_headers: response_headers.clone(),
};
let error = attach_failure_context(anyhow::anyhow!("Test error"), context.clone());
let extracted = extract_failure_context(&error);
assert_eq!(extracted.response_headers.len(), response_headers.len());
assert_eq!(extracted.response_headers, response_headers);
}
#[test]
fn test_failure_context_error_display_redirect_hop_count() {
let context = FailureContext {
final_url: Some("https://www.example.com".to_string()),
redirect_chain: vec![
"https://example.com".to_string(),
"https://www.example.com".to_string(),
],
response_headers: vec![],
};
let context_error = FailureContextError { context };
let display_msg = context_error.to_string();
assert!(display_msg.contains("hop"));
let hops = 2u32.saturating_sub(1);
assert_eq!(hops, 1);
}
#[test]
fn test_failure_context_error_display_single_redirect() {
let context = FailureContext {
final_url: Some("https://www.example.com".to_string()),
redirect_chain: vec![
"https://example.com".to_string(),
"https://www.example.com".to_string(),
],
response_headers: vec![],
};
let context_error = FailureContextError { context };
let display_msg = context_error.to_string();
assert!(display_msg.contains("www.example.com"));
assert!(display_msg.contains("example.com"));
assert!(display_msg.contains("hop"));
}
#[test]
fn test_attach_failure_context_preserves_error_chain() {
let original = anyhow::anyhow!("Original error")
.context("First context")
.context("Second context");
let context = FailureContext {
final_url: Some("https://example.com".to_string()),
redirect_chain: vec![],
response_headers: vec![],
};
let error_with_context = attach_failure_context(original, context);
let chain_msgs: Vec<String> = error_with_context.chain().map(|e| e.to_string()).collect();
let full_chain = chain_msgs.join(" | ");
assert!(
full_chain.contains("Original error")
|| full_chain.contains("First context")
|| full_chain.contains("Second context"),
"Original error chain should be preserved, got: {}",
full_chain
);
}
}