typestar

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

  1. serde_json::Error reports line, column and category.
  2. is_data means valid JSON that did not match your type.
  3. is_syntax means the text was not JSON at all.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 2 in Custom & failure, step 10 of 11 in Serde & JSON.

← Previous Next →