set_error/lib.rs
1#![deny(clippy::pedantic)]
2#![warn(missing_docs)]
3
4//! A very simple trait that overwrites errors.
5
6/// Import this trait to get the `set_error` method on `Result`s and `Option`s
7///
8/// # Examples
9/// ```
10/// use set_error::ChangeError;
11/// let foo: Option<u32> = None;
12/// assert_eq!(Err(String::from("erorr")), foo.set_error("erorr"));
13/// ```
14pub trait ChangeError<T> {
15 /// If an error is present it is replaced with the string passed into this method.
16 fn set_error(self, s: &str) -> Result<T, String>;
17}
18
19impl<T, E> ChangeError<T> for Result<T, E> {
20 fn set_error(self, s: &str) -> Result<T, String> {
21 match self {
22 Ok(t) => Ok(t),
23 Err(_) => Err(s.to_string()),
24 }
25 }
26}
27impl<T> ChangeError<T> for Option<T> {
28 fn set_error(self, s: &str) -> Result<T, String> {
29 match self {
30 Some(t) => Ok(t),
31 None => Err(s.to_string()),
32 }
33 }
34}