Hacker News new | ask | show | jobs
by joshka 959 days ago
I've been meaning to have a play with miette for a while:

    fn main() -> Result<()> {
        let config: Config = serde_json::from_str(DATA).map_err(|e| BadJson::from_json_err(e, DATA))?;
        Ok(())
    }

    #[derive(Debug, Error, Diagnostic)]
    #[error("Received some unexpected JSON.")]
    #[diagnostic(
        code(some::app::bad_json),
        url("https://my-app.com/some-json-error"),
        help("Fix the JSON.",)
    )]
    struct BadJson {
        source: serde_json::Error,
        #[source_code]
        json: NamedSource,
        #[label("here")]
        err_loc: (usize, usize),
    }

    impl BadJson {
        fn from_json_err(err: serde_json::error::Error, json: &str) -> Self {
            let offset = SourceOffset::from_location(json, err.line(), err.column());
            Self {
                source: err,
                json: NamedSource::new("config.json", json.to_string()),
                err_loc: (offset.offset(), 0),
            }
        }
    }
Generates:

    Error: some::app::bad_json (https://my-app.com/some-json-error)

    × Received some unexpected JSON.
    ╰─▶ invalid type: integer `123`, expected a string at line 13 column 51
        ╭─[config.json:12:1]
    12 │                             "color": "#f6f6f6",
    13 │                             "background-color": 123
        ·                                                   ▲
        ·                                                   ╰── here
    14 │                         }
        ╰────
    help: Fix the JSON.