Handling serde errors in Rust
A parse failure tells you what it wanted, and where it gave up.
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Step {
idx: u32,
title: String,
}
fn main() {
for raw in [r#"{"idx":1,"title":"ok"}"#, r#"{"idx":"one"}"#, "{oops"] {
match serde_json::from_str::<Step>(raw) {
Ok(step) => println!("parsed {:?}", step),
Err(e) => println!(
"line {} col {} data={} syntax={}",
e.line(),
e.column(),
e.is_data(),
e.is_syntax()
),
}
}
}
How it works
serde_json::Errorreports line, column and category.is_datameans valid JSON that did not match your type.is_syntaxmeans the text was not JSON at all.
Keywords and builtins used here
ErrOkStepStringfnforinmainmatchstructu32use
The run, in numbers
- Lines
- 22
- Characters to type
- 379
- Tokens
- 106
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 58 seconds.
Step 2 of 2 in Custom & failure, step 10 of 11 in Serde & JSON.