use std::fmt;
pub mod codes {
pub const OK: i32 = 0;
pub const FAILURE: i32 = 1;
pub const USAGE: i32 = 2;
pub const NOT_FOUND: i32 = 3;
pub const PERMISSION: i32 = 4;
pub const CANCELLED: i32 = 5;
}
#[derive(Debug, Clone)]
pub struct Error {
pub message: String,
pub code: i32,
pub notes: Vec<String>,
}
impl Error {
pub fn msg<S: Into<String>>(message: S) -> Self {
Error {
message: message.into(),
code: codes::FAILURE,
notes: Vec::new(),
}
}
pub fn usage<S: Into<String>>(message: S) -> Self {
Error {
message: message.into(),
code: codes::USAGE,
notes: Vec::new(),
}
}
pub fn not_found<S: Into<String>>(message: S) -> Self {
Error {
message: message.into(),
code: codes::NOT_FOUND,
notes: Vec::new(),
}
}
pub fn permission<S: Into<String>>(message: S) -> Self {
Error {
message: message.into(),
code: codes::PERMISSION,
notes: Vec::new(),
}
}
pub fn cancelled<S: Into<String>>(message: S) -> Self {
Error {
message: message.into(),
code: codes::CANCELLED,
notes: Vec::new(),
}
}
pub fn with_code(mut self, code: i32) -> Self {
self.code = code;
self
}
pub fn note<S: Into<String>>(mut self, note: S) -> Self {
self.notes.push(note.into());
self
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.message)
}
}
impl std::error::Error for Error {}
macro_rules! from_std {
($($ty:path),* $(,)?) => {
$(
impl From<$ty> for Error {
fn from(e: $ty) -> Self {
Error::msg(e.to_string())
}
}
)*
};
}
from_std!(
std::io::Error,
std::num::ParseIntError,
std::num::ParseFloatError,
std::str::Utf8Error,
std::string::FromUtf8Error,
std::num::TryFromIntError,
);
impl Error {
pub fn wrap<E: std::fmt::Display>(e: E) -> Self {
Error::msg(e.to_string())
}
}
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Default, Clone)]
pub struct ErrorSet {
errors: Vec<Error>,
}
impl ErrorSet {
pub fn new() -> Self {
ErrorSet { errors: Vec::new() }
}
pub fn push(&mut self, e: Error) {
self.errors.push(e);
}
pub fn absorb<T>(&mut self, r: Result<T>) -> Option<T> {
match r {
Ok(v) => Some(v),
Err(e) => {
self.errors.push(e);
None
}
}
}
pub fn is_empty(&self) -> bool {
self.errors.is_empty()
}
pub fn len(&self) -> usize {
self.errors.len()
}
pub fn errors(&self) -> &[Error] {
&self.errors
}
pub fn into_result(self) -> Result<()> {
if self.errors.is_empty() {
return Ok(());
}
let code = self.errors.iter().map(|e| e.code).max().unwrap_or(codes::FAILURE);
let mut summary = Error::msg(format!("{} operation(s) failed", self.errors.len()))
.with_code(code);
for e in &self.errors {
summary.notes.push(e.message.clone());
for n in &e.notes {
summary.notes.push(format!(" {}", n));
}
}
Err(summary)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn constructors_set_codes() {
assert_eq!(Error::msg("x").code, codes::FAILURE);
assert_eq!(Error::usage("x").code, codes::USAGE);
assert_eq!(Error::not_found("x").code, codes::NOT_FOUND);
assert_eq!(Error::permission("x").code, codes::PERMISSION);
assert_eq!(Error::cancelled("x").code, codes::CANCELLED);
}
#[test]
fn error_set_collects_and_reports() {
let mut s = ErrorSet::new();
assert!(s.is_empty());
s.push(Error::usage("first"));
s.push(Error::not_found("second"));
assert_eq!(s.len(), 2);
let e = s.into_result().unwrap_err();
assert_eq!(e.code, codes::NOT_FOUND);
assert_eq!(e.notes.len(), 2);
}
#[test]
fn empty_error_set_is_ok() {
assert!(ErrorSet::new().into_result().is_ok());
}
#[test]
fn absorb_returns_ok_value() {
let mut s = ErrorSet::new();
let v = s.absorb(Ok::<i32, Error>(5));
assert_eq!(v, Some(5));
let n = s.absorb(Err::<i32, Error>(Error::msg("bad")));
assert_eq!(n, None);
assert_eq!(s.len(), 1);
}
#[test]
fn io_error_converts() {
let io = std::io::Error::new(std::io::ErrorKind::NotFound, "nope");
let e: Error = io.into();
assert_eq!(e.code, codes::FAILURE);
}
}