use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
ConfigInvalid,
Unsupported,
Unexpected,
}
impl fmt::Display for ErrorKind {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::ConfigInvalid => "ConfigInvalid",
Self::Unsupported => "Unsupported",
Self::Unexpected => "Unexpected",
})
}
}
pub struct Error {
kind: ErrorKind,
message: String,
source: Option<String>,
}
impl Error {
pub fn kind(&self) -> ErrorKind {
self.kind
}
pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
source: None,
}
}
pub(crate) fn with_source(mut self, source: impl fmt::Display) -> Self {
self.source = Some(source.to_string());
self
}
}
impl fmt::Debug for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if formatter.alternate() {
return formatter
.debug_struct("Error")
.field("kind", &self.kind)
.field("message", &self.message)
.field("source", &self.source)
.finish();
}
write!(formatter, "{} => {}", self.kind, self.message)?;
if let Some(source) = &self.source {
write!(formatter, "\n\nSource:\n {source}")?;
}
Ok(())
}
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}", self.kind)?;
if !self.message.is_empty() {
write!(formatter, " => {}", self.message)?;
}
if let Some(source) = &self.source {
write!(formatter, ", source: {source}")?;
}
Ok(())
}
}
impl std::error::Error for Error {}