dtolnay / path-to-error

Find out path at which a deserialization error occurred
Apache License 2.0
320 stars 12 forks source link

Support path to Serialize error #11

Closed dtolnay closed 3 years ago

dtolnay commented 3 years ago

The current version of this library works for Deserialize errors only. I'd like to use it for Serialize too, which can also be fallible. For example I'd like to be able to determine the path to the following errors:

#[test]
fn test_refcell_already_borrowed() {
    #[derive(Serialize, Debug)]
    struct Outer<'a> {
        k: Inner<'a>,
    }

    #[derive(Serialize, Debug)]
    struct Inner<'a> {
        refcell: &'a RefCell<String>,
    }

    let refcell = RefCell::new(String::new());
    let outer = Outer {
        k: Inner { refcell: &refcell },
    };

    let _borrowed = refcell.borrow_mut();

    let mut out = Vec::new();
    let ser = &mut serde_json::Serializer::new(&mut out);
    let result = serde_path_to_error::serialize(&outer, ser);
    let path = result.unwrap_err().path().to_string();
    assert_eq!(path, "k.refcell");
}
#[test]
fn test_map_nonstring_key() {
    let mut inner_map = BTreeMap::new();
    inner_map.insert(b"", 0);

    let mut outer_map = BTreeMap::new();
    outer_map.insert("k", inner_map);

    let mut out = Vec::new();
    let ser = &mut serde_json::Serializer::new(&mut out);
    let result = serde_path_to_error::serialize(&outer_map, ser);
    let path = result.unwrap_err().path().to_string();
    assert_eq!(path, "k");
}