use std::error::Error;
use std::fmt;
#[derive(Debug)]
pub struct ConfigError {
message: String,
context: Option<String>,
source: Option<Box<dyn Error + Send + Sync + 'static>>,
kind: Option<String>,
}
impl ConfigError {
pub fn new(msg: impl Into<String>) -> Self {
Self {
message: msg.into(),
context: None,
source: None,
kind: None,
}
}
pub fn with_context(mut self, ctx: impl Into<String>) -> Self {
self.context = Some(ctx.into());
self
}
pub fn with_kind(mut self, kind: impl Into<String>) -> Self {
self.kind = Some(kind.into());
self
}
pub fn with_source<E>(mut self, source: E) -> Self
where
E: Error + Send + Sync + 'static,
{
self.source = Some(Box::new(source));
self
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Configuration error")?;
if let Some(kind) = &self.kind {
write!(f, " [{}]", kind)?;
}
if let Some(ctx) = &self.context {
write!(f, " in {}", ctx)?;
}
write!(f, ": {}", self.message)
}
}
impl Error for ConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source
.as_ref()
.map(|boxed| boxed.as_ref() as &(dyn Error + 'static))
}
}