1use std::error::Error as StdError;
20use std::io;
21
22#[derive(Debug)]
25pub struct GoWrapped {
26 prefix: String,
27 source: Box<dyn StdError + Send + Sync>,
28}
29
30impl GoWrapped {
31 pub fn new(
33 prefix: impl Into<String>,
34 source: impl Into<Box<dyn StdError + Send + Sync>>,
35 ) -> Self {
36 Self {
37 prefix: prefix.into(),
38 source: source.into(),
39 }
40 }
41}
42
43impl std::fmt::Display for GoWrapped {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 write!(f, "{}: {}", self.prefix, self.source)
46 }
47}
48
49impl StdError for GoWrapped {
50 fn source(&self) -> Option<&(dyn StdError + 'static)> {
51 Some(self.source.as_ref())
52 }
53}
54
55pub fn go_errno_text(err: &io::Error) -> String {
59 let Some(code) = err.raw_os_error() else {
60 return err.to_string();
61 };
62 let text = io::Error::from_raw_os_error(code).to_string();
63 let text = match text.rfind(" (os error ") {
64 Some(i) => &text[..i],
65 None => text.as_str(),
66 };
67 let mut chars = text.chars();
68 match chars.next() {
69 Some(first) => first.to_lowercase().chain(chars).collect(),
70 None => String::new(),
71 }
72}
73
74#[cfg(test)]
75mod tests {
76 use std::error::Error as StdError;
77 use std::io;
78
79 use super::{GoWrapped, go_errno_text};
80
81 #[derive(Debug)]
82 struct Cause;
83
84 impl std::fmt::Display for Cause {
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 f.write_str("root cause")
87 }
88 }
89
90 impl StdError for Cause {}
91
92 #[test]
93 fn display_is_prefix_colon_source() {
94 assert_eq!(
95 GoWrapped::new("failed to get session", Cause).to_string(),
96 "failed to get session: root cause"
97 );
98 assert_eq!(GoWrapped::new("", "x").to_string(), ": x");
99 let nested = GoWrapped::new("outer", GoWrapped::new("inner", "leaf"));
100 assert_eq!(nested.to_string(), "outer: inner: leaf");
101 }
102
103 #[test]
104 fn source_is_the_wrapped_cause() {
105 let err = GoWrapped::new("outer", GoWrapped::new("inner", Cause));
106 let inner = err.source().expect("outer has a source");
107 assert_eq!(inner.to_string(), "inner: root cause");
108 assert!(inner.is::<GoWrapped>());
109 let root = inner.source().expect("inner has a source");
110 assert!(root.is::<Cause>());
111 assert!(root.source().is_none());
112 }
113
114 #[test]
115 fn is_send_sync_static() {
116 fn assert_bounds<T: StdError + Send + Sync + 'static>() {}
117 assert_bounds::<GoWrapped>();
118 }
119
120 #[test]
121 fn errno_text_is_lowercased_strerror() {
122 assert_eq!(
123 go_errno_text(&io::Error::from_raw_os_error(2)),
124 "no such file or directory"
125 );
126 assert_eq!(
127 go_errno_text(&io::Error::from_raw_os_error(13)),
128 "permission denied"
129 );
130 assert_eq!(
131 go_errno_text(&io::Error::from_raw_os_error(21)),
132 "is a directory"
133 );
134 assert_eq!(go_errno_text(&io::Error::other("custom")), "custom");
135 }
136}