From 2902a2337c2e36a5d8e0e54b007d6100cca0c9ff Mon Sep 17 00:00:00 2001 From: Gal Schlezinger Date: Wed, 13 Nov 2024 19:57:24 +0200 Subject: [PATCH] docs(examples): add serde_json integration example (#407) --- Cargo.toml | 5 +++++ examples/serde_json.rs | 48 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 examples/serde_json.rs diff --git a/Cargo.toml b/Cargo.toml index 7678079..70d7859 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,6 +41,7 @@ syn = { version = "2.0.48", features = ["full"] } regex = "1.10" lazy_static = "1.4" +serde = { version = "1.0.196", features = ["derive"] } serde_json = "1.0.113" strip-ansi-escapes = "0.2.0" @@ -70,3 +71,7 @@ members = ["miette-derive"] [package.metadata.docs.rs] all-features = true + +[[example]] +name = "serde_json" +required-features = ["fancy"] diff --git a/examples/serde_json.rs b/examples/serde_json.rs new file mode 100644 index 0000000..d57a76a --- /dev/null +++ b/examples/serde_json.rs @@ -0,0 +1,48 @@ +//! This example shows how to integrate miette with serde_json +//! so the decoding source will be annotated with the decoding error, +//! providing contextual information about the error. + +use miette::{IntoDiagnostic, SourceOffset}; +use serde_json::{self, json}; + +#[derive(Debug, serde::Deserialize)] +struct Library { + #[allow(unused)] + name: String, +} + +#[derive(Debug, thiserror::Error, miette::Diagnostic)] +#[error("malformed json provided")] +struct SerdeError { + cause: serde_json::Error, + #[source_code] + input: String, + #[label("{cause}")] + location: SourceOffset, +} + +impl SerdeError { + /// Takes the input and the `serde_json::Error` and returns a SerdeError + /// that can be rendered nicely with miette. + pub fn from_serde_error(input: impl Into, cause: serde_json::Error) -> Self { + let input = input.into(); + let location = SourceOffset::from_location(&input, cause.line(), cause.column()); + Self { + cause, + input, + location, + } + } +} + +fn main() -> miette::Result<()> { + let input = serde_json::to_string_pretty(&json!({ + "name": 123 + })) + .into_diagnostic()?; + + let _library: Library = + serde_json::from_str(&input).map_err(|cause| SerdeError::from_serde_error(input, cause))?; + + Ok(()) +}