use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
Io {
path: PathBuf,
source: io::Error,
},
Parse {
path: PathBuf,
message: String,
},
Invalid(String),
}
impl Error {
pub fn io(path: impl AsRef<Path>, source: io::Error) -> Self {
Error::Io {
path: path.as_ref().to_path_buf(),
source,
}
}
pub fn parse(path: impl AsRef<Path>, message: impl fmt::Display) -> Self {
Error::Parse {
path: path.as_ref().to_path_buf(),
message: message.to_string(),
}
}
pub fn invalid(message: impl fmt::Display) -> Self {
Error::Invalid(message.to_string())
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Io { path, source } => write!(f, "{}: {source}", path.display()),
Error::Parse { path, message } => write!(f, "{}: {message}", path.display()),
Error::Invalid(message) => write!(f, "{message}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Io { source, .. } => Some(source),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn io_errors_name_the_path() {
let e = Error::io(
"settings.json",
io::Error::new(io::ErrorKind::NotFound, "nope"),
);
assert!(e.to_string().starts_with("settings.json: "), "got: {e}");
}
#[test]
fn invalid_errors_are_the_message_alone() {
assert_eq!(Error::invalid("no end marker").to_string(), "no end marker");
}
}