use thiserror::Error;
#[derive(Debug, Error)]
pub enum CommonError {
#[error("invalid argument: {0}")]
InvalidArgument(String),
#[error("value out of range: {0}")]
OutOfRange(String),
#[error("borsh (de)serialization error: {0}")]
Borsh(String),
#[error("json (de)serialization error: {0}")]
Json(String),
#[error("toml parse error: {0}")]
Toml(String),
#[error("config error: {0}")]
Config(String),
#[error("io error: {0}")]
Io(#[from] std::io::Error),
}
impl From<serde_json::Error> for CommonError {
fn from(e: serde_json::Error) -> Self {
CommonError::Json(e.to_string())
}
}
pub type Result<T, E = CommonError> = std::result::Result<T, E>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_messages_include_context() {
let e = CommonError::InvalidArgument("x must be positive".into());
assert_eq!(e.to_string(), "invalid argument: x must be positive");
}
#[test]
fn out_of_range_formats() {
let e = CommonError::OutOfRange("height > u64::MAX".into());
assert!(e.to_string().contains("out of range"));
}
#[test]
fn io_error_conversion() {
let io = std::io::Error::new(std::io::ErrorKind::NotFound, "nope");
let e: CommonError = io.into();
assert!(matches!(e, CommonError::Io(_)));
}
}