simple-error is a Rust library that provides a simple Error type backed by a String. It is best used when all you care about the error is an error string.
To use simple-error, first add this to your Cargo.toml:
[dependencies]
simple-error = "0.3"Then import what you use (Rust 2018/2021):
use simple_error::{SimpleError, try_with};// Add others as needed: require_with, ensure_with, bail, simple_error, map_err_withNow you can use simple-error in different ways:
You can use it simply as a string error type:
fndo_foo() -> Result<(),SimpleError>{Err(SimpleError::new("cannot do foo"))}You can use it to replace all error types if you only care about a string description:
fndo_bar() -> Result<(),SimpleError>{Err(SimpleError::from(std::io::Error::new(std::io::ErrorKind::Other,"oh no")))}Or you can chain all the errors, and get a complete error description at the top level:
fnfind_tv_remote() -> Result<(),SimpleError>{try_with!(std::fs::File::open("remotefile"),"failed to open remote file");Ok(())}fnturn_on_tv() -> Result<(), std::io::Error>{Ok(())}fnwatch_tv() -> Result<(),SimpleError>{try_with!(find_tv_remote(),"tv remote not found");try_with!(turn_on_tv(),"cannot turn on tv");Ok(())}fnstudy() -> Result<(),SimpleError>{Ok(())}fnrun() -> Result<(),SimpleError>{try_with!(study(),"cannot study");try_with!(watch_tv(),"cannot watch tv");Ok(())}fnmain(){ifletErr(e) = run(){println!("{}", e);}}// This prints out "cannot watch tv, tv remote not found, failed to open remote file, Text file busy" if the error is text file busy.You can also ensure a condition holds and early-return a SimpleError if it does not:
use simple_error::{SimpleError, ensure_with};fncheck_config(is_valid:bool) -> Result<(),SimpleError>{ensure_with!(is_valid,"invalid config");Ok(())}try_with!— unwrapResult, else returnSimpleError::with.require_with!— unwrapOption, else returnSimpleError::new.ensure_with!— assert boolean, else returnSimpleError::new.bail!— return early with aSimpleError(supports format/expr).simple_error!— construct aSimpleError(supports format/expr).map_err_with!— map aResult’s error with extra context.