1use std::fmt;
8use std::io;
9
10#[derive(Debug)]
12pub enum ForgeError {
13 UnknownEncoding,
15 DecodeError(String),
18 TooLarge { size: u64, max: u64 },
20 Io(io::Error),
22 Fetch(String),
24}
25
26impl ForgeError {
27 pub fn category(&self) -> &'static str {
30 match self {
31 ForgeError::UnknownEncoding => "unknown",
32 ForgeError::DecodeError(_) => "decode_error",
33 ForgeError::TooLarge { .. } => "too_large",
34 ForgeError::Io(_) => "io_error",
35 ForgeError::Fetch(_) => "fetch_error",
36 }
37 }
38}
39
40impl fmt::Display for ForgeError {
41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42 match self {
43 ForgeError::UnknownEncoding => write!(f, "unknown encoding (never guessed)"),
44 ForgeError::DecodeError(detail) => write!(f, "strict decode failed: {detail}"),
45 ForgeError::TooLarge { size, max } => {
46 write!(f, "file too large: {size} bytes > --max-file-size {max}")
47 }
48 ForgeError::Io(e) => write!(f, "io error: {e}"),
49 ForgeError::Fetch(e) => write!(f, "fetch error: {e}"),
50 }
51 }
52}
53
54impl std::error::Error for ForgeError {
55 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
56 match self {
57 ForgeError::Io(e) => Some(e),
58 _ => None,
59 }
60 }
61}
62
63impl From<io::Error> for ForgeError {
64 fn from(e: io::Error) -> Self {
65 ForgeError::Io(e)
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 #[test]
74 fn categories_match_report_schema() {
75 assert_eq!(ForgeError::UnknownEncoding.category(), "unknown");
76 assert_eq!(ForgeError::DecodeError("x".into()).category(), "decode_error");
77 assert_eq!(
78 ForgeError::TooLarge { size: 10, max: 5 }.category(),
79 "too_large"
80 );
81 assert_eq!(
82 ForgeError::Io(io::Error::new(io::ErrorKind::Other, "x")).category(),
83 "io_error"
84 );
85 assert_eq!(ForgeError::Fetch("x".into()).category(), "fetch_error");
86 }
87}