use std::fmt::{Display, Formatter};
#[derive(Debug)]
pub struct OperationError {
pub message: String,
}
impl OperationError {
pub(crate) fn new(message: &str) -> OperationError {
OperationError {
message: message.to_string(),
}
}
}
impl Display for OperationError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for OperationError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_operation_error_new_sets_message() {
let err = OperationError::new("test message");
assert_eq!(err.message, String::from("test message"));
}
#[test]
fn test_operation_error_new_empty_message() {
let err = OperationError::new("");
assert_eq!(err.message, String::from(""));
}
#[test]
fn test_display_matches_message() {
let err = OperationError::new("index out of bounds");
assert_eq!(format!("{}", err), "index out of bounds");
}
#[test]
fn test_can_propagate_as_std_error() {
fn fallible() -> Result<(), Box<dyn std::error::Error>> {
Err(OperationError::new("boom"))?
}
let e = fallible().unwrap_err();
assert_eq!(e.to_string(), "boom");
assert!(e.downcast_ref::<OperationError>().is_some());
}
}
pub struct ValueError {
pub message: String,
}