-
-
Notifications
You must be signed in to change notification settings - Fork 137
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support custom string for None/Some(T) #59
Comments
Could you show an example of what you would like to be able to write? Nothing in thiserror automatically puts "None" or "Some" into the display string, that must be from using {:?} on the field in your format string. |
I guess I meant that for the type Example: #[derive(Error)]
pub enum MyError {
#[error(
1.Some:"a variant error occurred with {1}: {0}";
1.None:"there was an empty variant error: {0}"
)]
Variant(String, Option<usize>)
} |
I would prefer not to build fancier support for this into thiserror. For now you can handwrite the Display impl, or make this work using the existing features depending on your preference. #[derive(Error, Debug)]
pub enum MyError {
Variant(String, Option<usize>)
}
impl Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
MyError::Variant(a, Some(b)) => {
write!(f, "a variant error occurred with {}: {}", b, a)
}
MyError::Variant(a, None) => {
write!(f, "there was an empty variant error: {}", a)
}
}
}
} #[derive(Error, Debug)]
pub enum MyError {
#[error("{}: {0}", match .1 {
Some(n) => format!("a variant error occurred with {}", n),
None => format!("there was an empty variant error"),
})]
Variant(String, Option<usize>),
} |
Would it be possible to get the second one into the documentation? I didn't even know that existed. |
I believe this is largely covered by the third bullet of https://github.com/dtolnay/thiserror/tree/ff9524e1fd65fc49cfe905e9456c255e470fb239#details which mentions that format arguments may be arbitrary expressions, with multiple examples. |
Excellent, thanks. |
It would be very useful to be able to support specialized display strings for when an argument of an enum is of type
Option<T>
and is the variantNone
. This would also remove theSome(...)
from the display on theSome
variant.The text was updated successfully, but these errors were encountered: