Thiserror and partial colorization?

Hi !

I actually use a enum to define some error and I implement fmt::Display to personalize message with some part in some color using Colorize crate.
I was looking if we can do the same with the thiserror crate but I don't find anything about colorization in it ?

Have you already use part color in message with thiserror ?

use colored::Colorize;
use core::fmt;
...

pub enum MyError {
    ErrorA {
        compared: f64,
        value: f64,
    },
...
}

impl<'a> fmt::Display for MyError <'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self {
            MyError::ErrorA{ compared, value } => write!(
                f,
                "{} {} > {}",
                "Error A ".red(),
                compared,
                value.to_string().yellow()
            ),
...
    }
}

I don't think thiserror will add colouring for you via the proc macro.

But if you extract ErrorA variant into a struct you can impl display for that and then thiserror will display it for you. I'm pretty sure there is something like transparent to use the Display impl of ErrorA:

Yup, here's the spelling:

#[derive(Error, Debug)]
pub enum MyError {
    #[error(transparent)]
    ErrorA(ErrorA),  // source and Display delegate to ErrorA
}

Adapted from thiserror docs example using anyhow::Error for an Other variant.

Thank you for you answer.
Finally, it is the same at the end... Maybe I have less code to write without thiserror...

I think thiserror supports referring fields in arbitrary expression for the display formatting. did you try this?

use thiserror::Error;
use colored::Colorize;
#[derive(Debug, Error)]
pub enum MyError {
    #[error("{} {} > {}", "Error A ".red(), .compared, .value.to_string().yello())]
    ErrorA {
        compared: f64,
        value: f64,
    },
...
}
2 Likes

Thank you. Finally, simple solution. I do not use . before the value... and it works too...

 #[error( "{} {} {}",
                "ErrorA ".red(),
                compared,
                value.to_string().yellow())]

good to know this. thanks for sharing.