knowledge_base_crud/
error.rs1use knowledge_base_validation::Diagnostic;
2use std::fmt;
3use std::io;
4use std::path::PathBuf;
5
6#[derive(Debug)]
7#[non_exhaustive]
8pub enum Error {
9 Read { path: PathBuf, source: io::Error },
10 ParseStatementBatch { path: PathBuf, source: serde_yaml::Error },
11 InvalidRequest(String),
12 ParseEntity { path: PathBuf, source: serde_yaml::Error },
13 InvalidRepository(String),
14 Edit { path: PathBuf, message: String },
15 Validation(Vec<Diagnostic>),
16 Write { path: PathBuf, source: io::Error },
17 ConcurrentChange(PathBuf),
18 Commit { message: String },
19}
20
21impl fmt::Display for Error {
22 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
23 match self {
24 Self::Read { path, source } => write!(formatter, "cannot read {}: {source}", path.display()),
25 Self::ParseStatementBatch { path, source } => {
26 write!(formatter, "cannot parse statement manifest {}: {source}", path.display())
27 }
28 Self::InvalidRequest(message) => write!(formatter, "invalid mutation request: {message}"),
29 Self::ParseEntity { path, source } => {
30 write!(formatter, "cannot parse entity {}: {source}", path.display())
31 }
32 Self::InvalidRepository(message) => write!(formatter, "cannot query knowledge base: {message}"),
33 Self::Edit { path, message } => {
34 write!(formatter, "cannot edit resource {}: {message}", path.display())
35 }
36 Self::Validation(diagnostics) => {
37 writeln!(formatter, "mutation would not produce a valid knowledge base:")?;
38 for (index, diagnostic) in diagnostics.iter().enumerate() {
39 if index + 1 == diagnostics.len() {
40 write!(formatter, "{diagnostic}")?;
41 } else {
42 writeln!(formatter, "{diagnostic}")?;
43 }
44 }
45 Ok(())
46 }
47 Self::Write { path, source } => {
48 write!(formatter, "cannot write {}: {source}", path.display())
49 }
50 Self::ConcurrentChange(path) => {
51 write!(formatter, "resource changed while applying mutation: {}", path.display())
52 }
53 Self::Commit { message } => formatter.write_str(message),
54 }
55 }
56}
57
58impl std::error::Error for Error {
59 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
60 match self {
61 Self::Read { source, .. } | Self::Write { source, .. } => Some(source),
62 Self::ParseStatementBatch { source, .. } | Self::ParseEntity { source, .. } => Some(source),
63 Self::InvalidRequest(_) | Self::InvalidRepository(_) | Self::Edit { .. } | Self::Validation(_) | Self::ConcurrentChange(_) | Self::Commit { .. } => None,
64 }
65 }
66}