morethantext-web/src/morethantext/error.rs

91 lines
1.9 KiB
Rust

use std::{error::Error, fmt};
#[derive(Debug)]
pub struct DBError {
msg: String,
src: Option<Box<dyn Error + 'static>>,
}
impl DBError {
pub fn new<S>(msg: S) -> Self
where
S: Into<String>,
{
Self {
msg: msg.into(),
src: None,
}
}
pub fn add_source<E>(&mut self, src: E)
where
E: Error + 'static,
{
self.src = Some(Box::new(src));
}
}
impl Error for DBError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match &self.src {
Some(err) => Some(err.as_ref()),
None => None,
}
}
}
impl fmt::Display for DBError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.msg)
}
}
#[cfg(test)]
mod create {
use super::*;
#[test]
fn with_str() {
let msg = "something happened";
let err = DBError::new(msg);
assert!(
err.to_string() == msg,
"Got: {} -- Want: {}",
err.to_string(),
msg
);
assert!(
err.source().is_none(),
"Error should initialize with no source."
);
}
#[test]
fn with_string() {
let msg = "it went boom".to_string();
let err = DBError::new(msg.clone());
assert!(
err.to_string() == msg,
"Got: {} -- Want: {}",
err.to_string(),
msg
);
assert!(
err.source().is_none(),
"Error should initialize with no source."
);
}
#[test]
fn with_source() {
let msg = "but this caused the problem";
let mut par = DBError::new("parent error");
let src = DBError::new(msg);
par.add_source(src);
let output = par.source();
assert!(output.is_some(), "Should return source.");
let source = output.unwrap();
assert!(source.to_string() == msg);
}
}