Simple String Errors
An easy way of doing error handling in rust is by returning String
as a Box<std::error::Error>
.
If the rust main
function returns an Err()
, this Err()
will be displayed with std::fmt::Debug
.
As you can see by running the example (by pressing the "Play" button in upper right of the code block),
this only
prints out the last Error
.
Error: "func1 error"
The next chapters of this tutorial show how chainerror
adds more information
and improves inspecting the sources of an error.
You can also run the tutorial examples in the checked out chainerror git repo.
$ cargo run -q --example tutorial1
#![allow(clippy::single_match)] #![allow(clippy::redundant_pattern_matching)] use std::error::Error; use std::io; fn do_some_io() -> Result<(), Box<dyn Error + Send + Sync>> { Err(io::Error::from(io::ErrorKind::NotFound))?; Ok(()) } fn func2() -> Result<(), Box<dyn Error + Send + Sync>> { if let Err(_) = do_some_io() { Err("func2 error")?; } Ok(()) } fn func1() -> Result<(), Box<dyn Error + Send + Sync>> { if let Err(_) = func2() { Err("func1 error")?; } Ok(()) } fn main() -> Result<(), Box<dyn Error + Send + Sync>> { func1() }