qubit_metadata/metadata_error.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026.
4 * Haixing Hu, Qubit Co. Ltd.
5 *
6 * All rights reserved.
7 *
8 ******************************************************************************/
9//! [`MetadataError`] — failures from explicit `Metadata` accessors.
10
11use std::fmt;
12
13use serde_json::Value;
14
15use crate::metadata_value_type::MetadataValueType;
16
17/// Errors produced by explicit `Metadata` accessors such as
18/// [`Metadata::try_get`](crate::Metadata::try_get) and
19/// [`Metadata::try_set`](crate::Metadata::try_set).
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub enum MetadataError {
22 /// The requested key does not exist.
23 MissingKey(String),
24 /// Serialization into [`serde_json::Value`] failed while storing a value.
25 SerializationError {
26 /// Metadata key being written.
27 key: String,
28 /// Human-readable serde error message.
29 message: String,
30 },
31 /// Deserialization from [`serde_json::Value`] failed while loading a value.
32 DeserializationError {
33 /// Metadata key being read.
34 key: String,
35 /// Fully-qualified Rust type name requested by the caller.
36 expected: &'static str,
37 /// Actual JSON value type stored under the key.
38 actual: MetadataValueType,
39 /// Human-readable serde error message.
40 message: String,
41 },
42}
43
44impl MetadataError {
45 /// Constructs a deserialization error for key `key`.
46 #[inline]
47 pub(crate) fn deserialization_error<T>(
48 key: &str,
49 value: &Value,
50 error: serde_json::Error,
51 ) -> Self {
52 Self::DeserializationError {
53 key: key.to_string(),
54 expected: std::any::type_name::<T>(),
55 actual: MetadataValueType::of(value),
56 message: error.to_string(),
57 }
58 }
59
60 /// Constructs a serialization error for key `key`.
61 #[inline]
62 pub(crate) fn serialization_error(key: String, error: serde_json::Error) -> Self {
63 Self::SerializationError {
64 key,
65 message: error.to_string(),
66 }
67 }
68}
69
70impl fmt::Display for MetadataError {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 match self {
73 Self::MissingKey(key) => write!(f, "Metadata key not found: {key}"),
74 Self::SerializationError { key, message } => {
75 write!(f, "Failed to serialize metadata value for key '{key}': {message}")
76 }
77 Self::DeserializationError {
78 key,
79 expected,
80 actual,
81 message,
82 } => write!(
83 f,
84 "Failed to deserialize metadata key '{key}' as {expected} from JSON {actual}: {message}"
85 ),
86 }
87 }
88}
89
90impl std::error::Error for MetadataError {}