Skip to content

Improve errors upon deserializing NonZero* #2158

Closed
@fulara

Description

@fulara

Deserializing errors on NonZero* could definitely be improved, not sure if this is possible, but somehow the normal numerical types have better information attached to them - is this fault of the wrappers - probably not.

silly example code
#[derive(Deserialize)]
struct Example {
    a: i32,
    b: i32,
    c: i32,
    d: i32,
    e: i32,
    f: i32,
    g: i32,
    h: i32,
    i: i32,
    j: i32,
    k: i32,
    l: i32,
    m: i32,
    n: i32,
    non_zero_usize: NonZeroUsize,
    usize: usize,
}

#[derive(Deserialize)]
struct Parent {
    example: Example,
}

#[test]
fn test() {
    let x = r#"
example:
  a: 0
  b: 0
  c: 0
  d: 0
  e: 0
  f: 0
  g: 0
  h: 0
  i: 0
  j: 0
  k: 0
  l: 0
  m: 0
  n: 0
  non_zero_usize: 1
  usize: 1
"#;
    let parsed: Parent = serde_yaml::from_str(x).unwrap();
}

When setting the non_zero_usize to '0' - misleading error.

expected a non-zero value", Some(Pos { marker: Marker { index: 13, line: 3, col: 3 }, path: "example" })

When setting the usize to '-1' - Nice error!

"invalid value: integer `-1`, expected usize", Some(Pos { marker: Marker { index: 137, line: 18, col: 9 }, path: "example.usize" })

As you can passing zero to non_zero_usize causes serde not to deserialize as expected but errors are hard to diagnose.
Following area could be improved:

  1. Path of the last node is swallowed, ( it says just example - unlike for usize where it says example.usize )
  2. The line is pointing at god knows what confusing readers.

When a person that has no access to the codebase encounters those errors it's almost impossible to guess what's the cause of the problem

Activity

dtolnay

dtolnay commented on Jan 21, 2022

@dtolnay
Member

I published a fix in serde 1.0.134.

added a commit that references this issue on Sep 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      Participants

      @dtolnay@fulara

      Issue actions

        Improve errors upon deserializing NonZero* · Issue #2158 · serde-rs/serde