use anyhow::{bail, Context, Error, Result}; use std::{boxed, fs}; use std::io::Read; use thiserror::Error; // #[derive(Clone, Debug, Eq, Error, PartialEq)] // #[error("Found no username in {0}")] #[derive(Debug,Error)] #[error("Found no username in {0}")] struct EmptyUsernameError(String); fn read_username(path: &str) ->Box<dyn std::error::Error>{ return Box::new(EmptyUsernameError(path.to_string())); } fn main() { //fs::write("config.dat", "").unwrap(); println!("{:?}", read_username("config.dat")) ; }
结合https://docs.rs/thiserror/latest/thiserror/ 一起看。
#[derive(Debug,Error)] #[error("Found no username in {0}")]
这两个缺一不可