Constant error type possible?

I'm converting something to use anyhow! type errors everywhere. I have some things that return Result<usefulvalue, &'static str>. About 10,000 such things, because they're generated by a code generator that generates marshaling code from a specification file. I want to return something that can still be 'static, preferably a constant because so many are the same message. anyhow! calls format!, which I don't need here.

Can't do this, that's a function call in a const:

const BADINPUT: anyhow::Error = anyhow!("Not good");

Can't do this, either:

const BADINPUT: std::io::Error = std::io::Error::new(std::io::ErrorKind::InvalidInput, "oh no!");

Is there some static struct which implements all the traits needed for std::io::error for which the structure is public, so it can just be created with something like:

const PROBLEM: SimpleErrorType: SimpleErrorType { msg: "Problem here" }

(Yes, I know I could define one and provide all the implementations myself. That's silly.)


It's really simple to do though:

pub struct MyError { msg: &'static str }

impl std::fmt::Display for MyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.msg)

// nothing needed in the impl block
impl std::error::Error for MyError {}

const PROBLEM: MyError = MyError { msg: "Problem here" };

Also, don't confuse the std::error::Error trait with the std::io::Error type. The first one is what anyhow is built on; the second one is used by the standard library primarily to represent error conditions reported by the OS.

[edit: fixed the write! invocation, sorry about that]

1 Like

OK. It's amazing that I have to write this, though.

thiserror, a sister crate of anyhow, can generate that implementation for you.

1 Like

Generally the expectation in Rust is that you will define custom error types to be returned from your own functions, not use prefab types. (Box<dyn std::error::Error> and anyhow::Error are exceptions.) Crates like thiserror can help streamline the process.