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