rust: I found myself always writing error messages like "failed to read/write…
- User
rust: I found myself always writing error messages like "failed to read/write file/directory" etc. with anyhow::anyhow!(). any crate has like a set of predefined error messages?
Assistant
You're not alone—this is a common pain point. While there isn't a widely-used crate that provides a canonical set of predefined error messages like
"failed to read file"or"failed to write directory", there are a few crates and patterns that can help reduce boilerplate and improve consistency.1.
thiserror+ Custom EnumIf you're writing a library or want structured errors,
thiserroris the go-to. You can define your own error enum with reusable messages:use thiserror::Error; #[derive(Error, Debug)] pub enum MyError { #[error("failed to read file: {0}")] ReadFile(std::io::Error), #[error("failed to write directory: {0}")] WriteDir(std::io::Error), }This gives you reusable, consistent messages and still lets you propagate underlying errors.
2. Macro Helper
If you're using
anyhowand just want to avoid repeating"failed to read file"etc., you can define a small macro:macro_rules! io_context { ($op:expr, $path:expr) => { anyhow::anyhow!("failed to {} {}", $op, $path.display()) }; } // Usage: return Err(io_context!("read file", path));This keeps things DRY and consistent.
3. Crates with Predefined I/O Errors
There’s no crate that gives you a full set of string error messages, but
fs-erris a drop-in replacement forstd::fsthat gives better error messages out of the box:use fs_err as fs; let content = fs::read_to_string("missing.txt")?;This will give you a message like:
No such file or directory (os error 2) at path "missing.txt"It’s not a predefined message per se, but it’s more informative than
std::fs.
Summary
- Use
thiserrorfor structured, reusable error messages. - Use a macro or helper fn if you're sticking with
anyhow. - Consider
fs-errfor better I/O error messages without extra work.
Let me know if you want a macro that auto-generates messages like
"failed to read file at {path}"withanyhow::Context.- Use
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.