json
json copied to clipboard
Return field name for semantic (Category::Data) errors
It would be very useful to have access to the field name in which a semantic (Category::Data
) error occurred. For example, the structure:
#[derive(Deserialize)]
struct MyData {
number: u8,
}
applied to the data:
{ "number": -1 }
gives a somewhat unhelpful error message Error("invalid value: integer
-1, expected u8", line: 1, column: 14)
[playground].
This is especially problematic because the given column is the column of the actual value in question, not the beginning of the field name, so fairly complex logic is needed to "rewind" to the field name. Especially in contexts where confidentiality is important, it would be useful to be able to know the name of the field for which type validation failed without looking at the data myself.
Would it be desirable to add a method field(&self) -> Option<&str>
for Error
s of Category::Data
? If so, I'll put together a PR.
Right now you can already use serde_path_to_error
to extract which field caused the error. As a benefit it works right now and with any data format (also toml etc.).
This looks like a neat workaround, thank you!
Right now you can already use
serde_path_to_error
to extract which field caused the error. As a benefit it works right now and with any data format (also toml etc.).
Thank you for mentioning this, it made my day. Lack of a "verbose error mode" (like serde_path_to_error provides) for --debug builds had been driving me crazy until now.
Could you please consider mentioning the serde_path_to_error crate in the serde_json crate documentation or the introduction at https://serde.rs/? I bet most new users want to be able to use this feature. I understand why it is in a separate crate, but that makes it hard to discover.
Thanks again!
Ah it's related to my question #759 But is there a way @jonasbb to avoid having to implement a custom deserializer for each of the types ?
@Roms1383 Sorry, I cannot help. I don't understand what you are implementing.
@jonasbb so actually it's like having a query parameter order_by
that can be only asc
or desc
and getting more details during deserialization failure, but I guess I misunderstood the fact that it's more related to validation than deserialization.