How to get meaningful parsing error messages that include input string? #33
-
I think the ParseError message should include the Thanks for the awesome crate!! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
At present, I've personally faced scenarios where I wanted error messages to incorporate input strings, and would like to improve this. However, it appears to be a common practice in Rust not to include input strings in errors. If an error contains an input string, For example, when parsing a huge string literal into the following type #[derive(FromStr)]
#[display("{0}")]
enum Value {
Int(u32),
Bool(bool),
#[display("\"{0}\"")]
Str(String),
} The following is processed.
If However, seeing that the I wrote above that it appears to be common practice in Rust not to include input strings in errors, but more accurately, I feel that it is recommended that users be given the choice of whether or not to include input strings in errors. For example, if the error in trait FromStrEx: Sized {
type Err;
fn from_str_ex(s: &str) -> Result<Self, Self::Err>;
}
impl<T: FromStr> FromStrEx for T
where
T::Err: std::error::Error + Send + Sync + 'static,
{
type Err = anyhow::Error;
fn from_str_ex(s: &str) -> Result<Self, Self::Err> {
s.parse()
.with_context(|| format!("failed to parse `{}`", s))
}
}
fn main() {
println!("{:?}", u8::from_str_ex("500"));
/*
Err(failed to parse `500`
Caused by:
number too large to fit in target type)
*/
} Still, I do not believe that this error message is the best one, and there might be cases where the choices are unnecessary. So, in the future, (Note: While it's not possible to include input string in error message without memory allocation, type name can be incorporated.) |
Beta Was this translation helpful? Give feedback.
At present,
parse_display
lacks the functionality to produce meaningful error messages.I've personally faced scenarios where I wanted error messages to incorporate input strings, and would like to improve this.
However, it appears to be a common practice in Rust not to include input strings in errors.
This is the case for errors included in the standard library (e.g.
std::num::ParseIntError
),url
crate (e.g.url::ParseError
), andchrono
crate (e.g.chrono::format::ParseError
).If an error contains an input string,
String
must be created from the input&str
and included in the error, which is a performance disadvantage.So, I believe this practice is appropriate.
For example, when parsing…