Skip to content

Errors from Visitor should point to beginning of the object #287

@dtolnay

Description

@dtolnay

In the following string validation, the error message points to the close quote after "test123". It would be nicer to point to the opening quote instead.

#[macro_use]
extern crate serde_derive;

extern crate serde;
extern crate serde_json;

use std::fmt;
use serde::de::{self, Deserializer, Visitor};

#[derive(Deserialize, Debug)]
struct Esheri3 {
    #[serde(deserialize_with = "letters_only")]
    name: String,
}

fn letters_only<'de, D>(deserializer: D) -> Result<String, D::Error>
where
    D: Deserializer<'de>,
{
    struct NameVisitor;

    impl<'de> Visitor<'de> for NameVisitor {
        type Value = String;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("string containing only letters")
        }

        fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
        where
            E: de::Error,
        {
            if s.chars().all(char::is_alphabetic) {
                Ok(s.to_owned())
            } else {
                Err(de::Error::custom("name must only contain letters"))
            }
        }
    }

    deserializer.deserialize_string(NameVisitor)
}

fn main() {
    let j = r#"
        {
          "name": "test123"
        }
    "#;
    println!("{}", serde_json::from_str::<Esheri3>(j).unwrap_err());
}
name must only contain letters at line 3 column 27

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions