Skip to content

Instantly share code, notes, and snippets.

@iTrooz
Created August 26, 2025 17:12
Show Gist options
  • Save iTrooz/e564a17cb16408e964505373222d167e to your computer and use it in GitHub Desktop.
Save iTrooz/e564a17cb16408e964505373222d167e to your computer and use it in GitHub Desktop.
Error handling based on thiserror type, with a variant to catch "all other errors" using anyhow
//! Error handling based on thiserror type, with a variant to catch "all other errors" using anyhow.
use std::fs::read_to_string;
#[derive(thiserror::Error, Debug)]
pub enum MyError {
#[error("some other error")]
FileNotFound,
#[error("anyhow error: {0}")]
Anyhow(#[from] anyhow::Error),
}
fn into_anyhow<E: std::error::Error + Send + Sync + 'static>(err: E) -> anyhow::Error {
err.into()
}
fn read_file(path: &str) -> Result<String, MyError> {
let res = read_to_string(path);
match res {
Ok(contents) => Ok(contents),
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
Err(MyError::FileNotFound)
} else {
Err(into_anyhow(err))?
}
}
}
}
fn main() {
match read_file("test.txt") {
Ok(contents) => println!("File contents:\n{}", contents),
Err(e) => println!("Error: {}", e),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment