grafbase_sdk/types/
error.rs1use std::{borrow::Cow, collections::HashMap};
2
3use crate::{wit, SdkError};
4
5#[derive(Clone)]
7pub struct Error(wit::Error);
8
9impl std::fmt::Display for Error {
10 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11 write!(f, "{}", self.0.message)
12 }
13}
14
15impl std::fmt::Debug for Error {
16 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17 f.debug_struct("Error")
18 .field("message", &self.0.message)
19 .field(
20 "extensions",
21 &self
22 .0
23 .extensions
24 .iter()
25 .map(|(key, value)| {
26 (
27 key,
28 minicbor_serde::from_slice::<serde_json::Value>(value).unwrap_or_default(),
29 )
30 })
31 .collect::<HashMap<_, _>>(),
32 )
33 .finish()
34 }
35}
36
37impl From<Error> for wit::Error {
38 fn from(err: Error) -> Self {
39 err.0
40 }
41}
42
43impl Error {
44 #[inline]
46 pub fn new(message: impl Into<String>) -> Self {
47 Self(wit::Error {
48 message: message.into(),
49 extensions: Vec::new(),
50 })
51 }
52
53 #[inline]
55 pub fn with_extension(mut self, key: impl Into<String>, value: impl serde::Serialize) -> Result<Self, SdkError> {
56 let value = minicbor_serde::to_vec(&value)?;
57 self.0.extensions.push((key.into(), value));
58 Ok(self)
59 }
60}
61
62impl wit::Error {
63 pub(crate) fn new(message: impl Into<String>) -> Self {
64 Self {
65 message: message.into(),
66 extensions: Vec::new(),
67 }
68 }
69}
70
71impl From<String> for Error {
72 fn from(err: String) -> Self {
73 Error(wit::Error {
74 message: err,
75 extensions: Vec::new(),
76 })
77 }
78}
79
80impl From<&str> for Error {
81 fn from(err: &str) -> Self {
82 Error(wit::Error {
83 message: err.to_string(),
84 extensions: Vec::new(),
85 })
86 }
87}
88
89impl From<Cow<'_, str>> for Error {
90 fn from(err: Cow<'_, str>) -> Self {
91 Error(wit::Error {
92 message: err.into_owned(),
93 extensions: Vec::new(),
94 })
95 }
96}
97
98impl From<SdkError> for Error {
99 fn from(err: SdkError) -> Self {
100 Error(wit::Error {
101 message: err.to_string(),
102 extensions: Vec::new(),
103 })
104 }
105}
106
107impl From<wit::Error> for Error {
108 fn from(err: wit::Error) -> Self {
109 Error(err)
110 }
111}