Serde: how to ignore errors?

I am using serde to parse a JSON config. It's important for me that this never fails. Specifically, if a field can't be deserialized because the config is in the wrong format, I want to set this field to config::Default basically. Is it possible to do this with serde?

EDIT: naturally, I also want to collect the list of observed errors, and presnt the to the user

You can call unwrap_or_default on the result you got from serde.

That would set all fields to default values, and not only the problematic ones

Serde has field attributes to make this possible, either using the regular Default trait impl for the type or with a custom function.

1 Like

It only helps if attribute is missing, not if it has a wrong format.

Ie, something like this:

struct Config { value:  u32}

// config.json
  "value": "92"

The #[serde(deserialize_with = "path")] attribute can definitely take care of that too, as long as it's valid json.

Hm, indeed the attribute can help, if I annotate each field with the appropriate function, which also will have to duplicate my overall type's default... And I guess I won't get a list of errors that way?

Sure why not

You might be able to use DeserializeSeed although I don't really know how it works.