serde-rs / json

Strongly typed JSON library for Rust
Apache License 2.0
4.83k stars 552 forks source link

Return field name for semantic (Category::Data) errors #748

Open NoraCodes opened 3 years ago

NoraCodes commented 3 years ago

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 Errors of Category::Data? If so, I'll put together a PR.

jonasbb commented 3 years ago

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.).

NoraCodes commented 3 years ago

This looks like a neat workaround, thank you!

ghost commented 3 years ago

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!

Roms1383 commented 3 years ago

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 ?

jonasbb commented 3 years ago

@Roms1383 Sorry, I cannot help. I don't understand what you are implementing.

Roms1383 commented 3 years ago

@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.