pub const ERR_COMPACTION: &str = "context compaction failed";
#[derive(Debug)]
pub struct CompactionError {
detail: String,
source: Option<Box<dyn std::error::Error + Send + Sync>>,
}
impl CompactionError {
pub fn new(detail: impl Into<String>) -> Self {
Self {
detail: detail.into(),
source: None,
}
}
pub fn wrap(
context: impl Into<String>,
source: impl Into<Box<dyn std::error::Error + Send + Sync>>,
) -> Self {
let source = source.into();
Self {
detail: format!("{}: {}", context.into(), source),
source: Some(source),
}
}
pub fn detail(&self) -> &str {
&self.detail
}
}
impl std::fmt::Display for CompactionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{ERR_COMPACTION}: {}", self.detail)
}
}
impl std::error::Error for CompactionError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source
.as_deref()
.map(|e| e as &(dyn std::error::Error + 'static))
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
use std::error::Error as _;
#[test]
fn new_has_go_prefix_and_no_source() {
let e = CompactionError::new("post-invocation: compaction panicked: boom");
assert_eq!(
e.to_string(),
"context compaction failed: post-invocation: compaction panicked: boom"
);
assert_eq!(e.detail(), "post-invocation: compaction panicked: boom");
assert!(e.source().is_none());
}
#[test]
fn wrap_keeps_the_source_chain() {
let e = CompactionError::wrap("failed to append the summary event", "disk full");
assert_eq!(
e.to_string(),
"context compaction failed: failed to append the summary event: disk full"
);
assert_eq!(e.detail(), "failed to append the summary event: disk full");
assert_eq!(e.source().unwrap().to_string(), "disk full");
assert!(e.to_string().starts_with(&format!("{ERR_COMPACTION}: ")));
}
}