Sub topic 9
Reading and handling serde errors
This chapter assumes you can derive Serialize and Deserialize and call serde_json::from_str. It also assumes you are comfortable with Result and match.
Where errors come from
Serialization rarely fails. Deserialization fails often, because the input comes from outside your program. With serde_json, both directions return serde_json::Error. Other format crates define their own error types. They all follow the same pattern: a message plus a position in the input.
A serde_json::Error prints a message such as `missing field name at line 1 column 8`. It also has methods you can inspect:
line()andcolumn()give the position where parsing stopped. Both are 1-based, and both are 0 when no position applies.classify()returns aCategorythat says what kind of failure occurred.
The four categories
| Category | Meaning | Typical cause |
|---|---|---|
| `Syntax` | The input is not valid JSON | A stray comma or an unquoted key |
| `Data` | The JSON is valid but does not fit the type | A missing field, or a string where a number is expected |
| `Eof` | The input ended too early | A truncated file or network read |
| `Io` | Reading from the source failed | Only with reader-based functions such as `from_reader` |
The category tells you who is probably at fault. Data errors usually mean the sender and your type disagree about the schema. Eof often means a truncated download.
Inspecting an error
use serde::Deserialize;
use serde_json::error::Category;
#[derive(Debug, Deserialize)]
struct User {
id: u32,
name: String,
}
fn parse(input: &str) -> Result<User, serde_json::Error> {
serde_json::from_str(input)
}
fn main() {
let inputs = [
r#"{"id":1,"name":"Ada"}"#,
r#"{"id":1}"#,
r#"{"id":"one","name":"Ada"}"#,
r#"{"id":1,"name":"Ada""#,
r#"{"id":1,,}"#,
];
for input in inputs {
match parse(input) {
Ok(user) => println!("ok: {user:?}"),
Err(e) => {
let kind = match e.classify() {
Category::Io => "io",
Category::Syntax => "syntax",
Category::Data => "data",
Category::Eof => "eof",
};
println!("{kind} error at {}:{}: {e}", e.line(), e.column());
}
}
}
}Run it and you will see one success and four failures, one in each of Data (twice), Eof, and Syntax. Note that the missing name field and the wrong type for id are both Data errors.
Writing your own errors
A custom function can reject values that have the right type but the wrong content. Inside a Deserialize implementation or a deserialize_with function, use serde::de::Error::custom. It builds an error of whatever type the format uses.
use serde::de::{Deserializer, Error};
use serde::Deserialize;
fn non_empty<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
let s = String::deserialize(d)?;
if s.is_empty() {
Err(D::Error::custom("name must not be empty"))
} else {
Ok(s)
}
}
#[derive(Debug, Deserialize)]
struct Account {
#[serde(deserialize_with = "non_empty")]
name: String,
}
fn main() {
let result: Result<Account, _> = serde_json::from_str(r#"{"name":""}"#);
println!("{}", result.unwrap_err());
}The output is your message followed by the position, for example name must not be empty at line 1 column 11. This error is classified as Data.
Handling errors in applications
- Use
?to pass the error up.serde_json::Errorimplementsstd::error::Error, so it converts intoBox<dyn Error>. Libraries such asthiserrorcan wrap it with#[from]. - Log the whole error, not just a generic message. The line and column point at the problem.
- Do not return raw serde messages to end users of a public API. They name your internal field names and types.
Exercise
A program reads a JSON file and gets an error whose classify() is Eof. Which category would you expect if the file contained {"id": 1,} instead, and why?
Show answer
Syntax. The input is complete, so it is not Eof. But a trailing comma before } is not valid JSON, so the parser rejects it before it checks the data against your type.