grafbase_sdk/types/
error.rs1use std::{borrow::Cow, collections::HashMap};
2
3use crate::{SdkError, cbor, wit};
4
5#[derive(Clone)]
7pub struct Error(pub(crate) 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)| (key, cbor::from_slice::<serde_json::Value>(value).unwrap_or_default()))
26 .collect::<HashMap<_, _>>(),
27 )
28 .finish()
29 }
30}
31
32impl From<Error> for wit::Error {
33 fn from(err: Error) -> Self {
34 err.0
35 }
36}
37
38impl Error {
39 #[inline]
41 pub fn new(message: impl Into<String>) -> Self {
42 Self(wit::Error {
43 message: message.into(),
44 extensions: Vec::new(),
45 })
46 }
47
48 #[inline]
50 pub fn extension(mut self, key: impl Into<String>, value: impl serde::Serialize) -> Result<Self, SdkError> {
51 let value = crate::cbor::to_vec(&value)?;
52 self.0.extensions.push((key.into(), value));
53 Ok(self)
54 }
55}
56
57impl wit::Error {
58 pub(crate) fn new(message: impl Into<String>) -> Self {
59 Self {
60 message: message.into(),
61 extensions: Vec::new(),
62 }
63 }
64}
65
66impl From<String> for Error {
67 fn from(err: String) -> Self {
68 Error(wit::Error {
69 message: err,
70 extensions: Vec::new(),
71 })
72 }
73}
74
75impl From<&str> for Error {
76 fn from(err: &str) -> Self {
77 Error(wit::Error {
78 message: err.to_string(),
79 extensions: Vec::new(),
80 })
81 }
82}
83
84impl From<Cow<'_, str>> for Error {
85 fn from(err: Cow<'_, str>) -> Self {
86 Error(wit::Error {
87 message: err.into_owned(),
88 extensions: Vec::new(),
89 })
90 }
91}
92
93impl From<SdkError> for Error {
94 fn from(err: SdkError) -> Self {
95 Error(wit::Error {
96 message: err.to_string(),
97 extensions: Vec::new(),
98 })
99 }
100}
101
102impl From<wit::Error> for Error {
103 fn from(err: wit::Error) -> Self {
104 Error(err)
105 }
106}
107
108impl From<wit::HttpError> for Error {
109 fn from(err: wit::HttpError) -> Self {
110 match err {
111 wit::HttpError::Timeout => "HTTP request timed out".into(),
112 wit::HttpError::Request(err) => format!("Request error: {err}").into(),
113 wit::HttpError::Connect(err) => format!("Connection error: {err}").into(),
114 }
115 }
116}