tiny_error/lib.rs
1//! A tiny crate for error handling. It is able to convert items of the
2//! [`Error`](https://doc.rust-lang.org/std/error/trait.Error.html) trait into
3//! their messages, allowing for easy propagation.
4//!
5//! # Examples
6//!
7//! ```rust
8//! use tiny_error::ErrorMessage;
9//!
10//! use std::{
11//! env,
12//! fs,
13//! path::PathBuf,
14//! };
15//!
16//! fn main() -> Result<(), ErrorMessage> {
17//! // Text when failed:
18//! // Error: Invalid input
19//! // Correct Usage: `[crate_name] example/file/path.txt`
20//! let path = get_path()?;
21//! // Text when failed:
22//! // Error: No such file or directory (os error 2)
23//! let file = fs::read_to_string(path)?;
24//!
25//! Ok(())
26//! }
27//!
28//! // Gets the first argument passed. If none or more were, returns an
29//! // `ErrorMessage`.
30//! fn get_path() -> Result<PathBuf, ErrorMessage> {
31//! let mut args = env::args().skip(1);
32//! let arg = args.next().filter(|_| args.next().is_none());
33//!
34//! arg
35//! .map(|input| input.into())
36//! .ok_or_else(|| ErrorMessage::new(
37//! "Invalid input\n\
38//! Correct Usage: `[crate_name] example/file/path.txt`"
39//! ))
40//! }
41//! ```
42
43use std::{
44 error::Error,
45 fmt::{Debug, Formatter, Result as FmtResult},
46};
47
48/// The struct that holds the error message.
49pub struct ErrorMessage(String);
50
51impl ErrorMessage {
52 /// Constructs a new [`ErrorMessage`] with the passed parameter,
53 /// converting it into a [`String`](https://doc.rust-lang.org/std/string/struct.String.html).
54 pub fn new<S: Into<String>>(message: S) -> Self {
55 ErrorMessage(message.into())
56 }
57}
58
59impl Debug for ErrorMessage {
60 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
61 write!(f, "{}", self.0)
62 }
63}
64
65impl<E: Error> From<E> for ErrorMessage {
66 fn from(value: E) -> Self {
67 ErrorMessage(format!("{}", value))
68 }
69}