Skip to content
TheChatArchiveThe Chat Archive
Kimikimi-k2-0711-preview· Moonshot AIHugging Face LMArena Human Preference 140K

rust: I found myself always writing error messages like "failed to read/write…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-flash-lite-preview-06-17-thinking’s answer.
  1. 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?

  2. Kimi 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 Enum

    If you're writing a library or want structured errors, thiserror is 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 anyhow and 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-err is a drop-in replacement for std::fs that 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 thiserror for structured, reusable error messages.
    • Use a macro or helper fn if you're sticking with anyhow.
    • Consider fs-err for 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}" with anyhow::Context.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.