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.