use std::error::Error as StdError;
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
pub type Source = Box<dyn StdError + Send + Sync + 'static>;
#[derive(Debug)]
pub enum Error {
Read { path: PathBuf, source: io::Error },
Parse { source: Source },
PageCount { source: Source },
Serialize { source: Source },
Write { source: io::Error },
}
impl Error {
pub fn read(path: &Path, source: io::Error) -> Self {
Error::Read {
path: path.to_path_buf(),
source,
}
}
pub fn parse(source: impl Into<Source>) -> Self {
Error::Parse {
source: source.into(),
}
}
pub fn page_count(source: impl Into<Source>) -> Self {
Error::PageCount {
source: source.into(),
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Read { path, .. } => write!(f, "could not read {}", path.display()),
Error::Parse { .. } => write!(f, "could not parse the document as a PDF"),
Error::PageCount { .. } => write!(f, "could not count the pages of the document"),
Error::Serialize { .. } => write!(f, "could not render the report as JSON"),
Error::Write { .. } => write!(f, "could not write the report"),
}
}
}
impl StdError for Error {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Error::Parse { source } | Error::PageCount { source } | Error::Serialize { source } => {
Some(source.as_ref())
}
Error::Read { source, .. } => Some(source),
Error::Write { source } => Some(source),
}
}
}
impl From<serde_json::Error> for Error {
fn from(source: serde_json::Error) -> Self {
Error::Serialize {
source: Box::new(source),
}
}
}
impl From<io::Error> for Error {
fn from(source: io::Error) -> Self {
Error::Write { source }
}
}
pub fn report(e: &dyn StdError) -> String {
let mut out = format!("error: {e}\n");
let mut cause = e.source();
while let Some(c) = cause {
out.push_str(&format!(" caused by: {c}\n"));
cause = c.source();
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(Debug)]
struct Inner;
impl fmt::Display for Inner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "at byte 12043")
}
}
impl StdError for Inner {}
#[derive(Debug)]
struct Outer;
impl fmt::Display for Outer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "malformed object")
}
}
impl StdError for Outer {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(&Inner)
}
}
#[test]
fn names_the_file_it_could_not_read() {
let e = Error::read(
Path::new("/tmp/paper.pdf"),
io::Error::new(io::ErrorKind::NotFound, "no such file"),
);
assert_eq!(e.to_string(), "could not read /tmp/paper.pdf");
}
#[test]
fn the_message_does_not_repeat_the_cause() {
let e = Error::parse(Outer);
assert!(!e.to_string().contains("malformed"));
assert_eq!(
e.source().map(ToString::to_string).as_deref(),
Some("malformed object")
);
}
#[test]
fn report_walks_the_whole_chain() {
let e = Error::parse(Outer);
assert_eq!(
report(&e),
"error: could not parse the document as a PDF\n \
caused by: malformed object\n \
caused by: at byte 12043\n"
);
}
#[test]
fn a_missing_file_is_not_a_malformed_one() {
let missing = Error::read(
Path::new("nope.pdf"),
io::Error::new(io::ErrorKind::NotFound, "no such file"),
);
let corrupt = Error::parse(Outer);
assert!(missing.to_string().contains("nope.pdf"));
assert!(!corrupt.to_string().contains("read"));
assert!(matches!(missing, Error::Read { .. }));
assert!(matches!(corrupt, Error::Parse { .. }));
}
#[test]
fn a_broken_page_tree_is_not_reported_as_an_unreadable_file() {
let e = Error::page_count(Outer);
assert_eq!(e.to_string(), "could not count the pages of the document");
}
#[test]
fn io_and_serde_convert_so_the_question_mark_still_works() {
let io_err: Error = io::Error::new(io::ErrorKind::PermissionDenied, "denied").into();
assert!(matches!(io_err, Error::Write { .. }));
assert_eq!(io_err.to_string(), "could not write the report");
let map = std::collections::HashMap::from([((), 1i32)]);
let json_err: Error = serde_json::to_string(&map).unwrap_err().into();
assert!(matches!(json_err, Error::Serialize { .. }));
assert_eq!(json_err.to_string(), "could not render the report as JSON");
}
#[test]
fn the_original_error_is_still_reachable() {
let e = Error::page_count(io::Error::new(io::ErrorKind::UnexpectedEof, "eof"));
let src = e.source().expect("a source");
assert!(src.downcast_ref::<io::Error>().is_some());
}
#[test]
fn the_error_type_crosses_threads() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Error>();
}
}