use std::fmt;
use std::io;
#[derive(Debug)]
pub enum ForgeError {
UnknownEncoding,
DecodeError(String),
EncodeError(String),
TooLarge { size: u64, max: u64 },
Io(io::Error),
Fetch(String),
}
impl ForgeError {
pub fn category(&self) -> &'static str {
match self {
ForgeError::UnknownEncoding => "unknown",
ForgeError::DecodeError(_) => "decode_error",
ForgeError::EncodeError(_) => "encode_error",
ForgeError::TooLarge { .. } => "too_large",
ForgeError::Io(_) => "io_error",
ForgeError::Fetch(_) => "fetch_error",
}
}
}
impl fmt::Display for ForgeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ForgeError::UnknownEncoding => write!(f, "unknown encoding (never guessed)"),
ForgeError::DecodeError(detail) => write!(f, "strict decode failed: {detail}"),
ForgeError::EncodeError(detail) => write!(f, "strict encode failed: {detail}"),
ForgeError::TooLarge { size, max } => {
write!(f, "file too large: {size} bytes > --max-file-size {max}")
}
ForgeError::Io(e) => write!(f, "io error: {e}"),
ForgeError::Fetch(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for ForgeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
impl From<io::Error> for ForgeError {
fn from(e: io::Error) -> Self {
ForgeError::Io(e)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn categories_match_report_schema() {
assert_eq!(ForgeError::UnknownEncoding.category(), "unknown");
assert_eq!(
ForgeError::DecodeError("x".into()).category(),
"decode_error"
);
assert_eq!(
ForgeError::EncodeError("x".into()).category(),
"encode_error"
);
assert_eq!(
ForgeError::TooLarge { size: 10, max: 5 }.category(),
"too_large"
);
assert_eq!(ForgeError::Io(io::Error::other("x")).category(), "io_error");
assert_eq!(ForgeError::Fetch("x".into()).category(), "fetch_error");
}
}