Skip to main content

gadk_platform/
go_err.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Error wrapping with a prefix ([`GoWrapped`]) and OS error texts ([`go_errno_text`]), shared
17//! by the gadk crates that build error chains.
18
19use std::error::Error as StdError;
20use std::io;
21
22/// An error that displays `{prefix}: {source}` and keeps `source` as its `source()`, so walks
23/// of the error chain find the cause.
24#[derive(Debug)]
25pub struct GoWrapped {
26    prefix: String,
27    source: Box<dyn StdError + Send + Sync>,
28}
29
30impl GoWrapped {
31    /// Wraps `source` under `prefix`.
32    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
55/// The text of the OS error `err`: the C library's message for the OS error code with its first
56/// letter lowercased (e.g. `no such file or directory`, `permission denied`,
57/// `is a directory`); an error without an OS code keeps its own text.
58pub 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}