use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
InvalidArgument,
DimensionMismatch,
OptionsMismatch,
NotFound,
NotAnIndex,
IdInUse,
Locked,
ReadOnly,
Corrupt,
Full,
Io,
Other,
}
pub struct Error {
kind: ErrorKind,
inner: anyhow::Error,
}
impl Error {
pub fn kind(&self) -> ErrorKind {
self.kind
}
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:#}", self.inner)
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}: {self}", self.kind)
}
}
impl std::error::Error for Error {}
impl From<anyhow::Error> for Error {
fn from(inner: anyhow::Error) -> Self {
let raised = inner.chain().find_map(|cause| cause.downcast_ref::<Raised>());
let kind = match raised {
Some(raised) => raised.kind,
None if inner.chain().any(|cause| cause.is::<std::io::Error>()) => ErrorKind::Io,
None => ErrorKind::Other,
};
Self { kind, inner }
}
}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
anyhow::Error::from(e).into()
}
}
#[derive(Debug)]
pub(crate) struct Raised {
kind: ErrorKind,
message: String,
}
impl fmt::Display for Raised {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for Raised {}
pub(crate) fn raised(kind: ErrorKind, message: String) -> anyhow::Error {
anyhow::Error::new(Raised { kind, message })
}
macro_rules! fail {
($kind:ident, $($message:tt)+) => {
return Err($crate::error::raised(
$crate::error::ErrorKind::$kind,
format!($($message)+),
)
.into())
};
}
pub(crate) use fail;
#[cfg(test)]
mod tests {
use super::*;
use anyhow::Context;
fn raise() -> anyhow::Result<()> {
fail!(Locked, "{} is open", "x.chassis");
}
#[test]
fn test_a_kind_survives_context_and_the_message_keeps_every_cause() {
let error: Error = raise().context("Opening failed").unwrap_err().into();
assert_eq!(error.kind(), ErrorKind::Locked);
assert_eq!(error.to_string(), "Opening failed: x.chassis is open");
let io = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
let error: Error = anyhow::Error::from(io).context("Can't open x").into();
assert_eq!(
(error.kind(), error.to_string().as_str()),
(ErrorKind::Io, "Can't open x: denied")
);
let error: Error = anyhow::anyhow!("something").into();
assert_eq!(error.kind(), ErrorKind::Other);
let into: anyhow::Result<()> = (|| Err(Error::from(anyhow::anyhow!("x")))?)();
assert!(into.is_err());
}
}