Skip to main content

bedrock_agentcore/
error.rs

1use std::fmt;
2
3type BoxError = Box<dyn std::error::Error + Send + Sync>;
4
5/// The reason an SDK operation failed. Read it with [`Error::kind`].
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7#[non_exhaustive]
8pub enum ErrorKind {
9    /// The server could not bind its listen address, for example because the port is in use.
10    Bind,
11    /// The server could not install its shutdown signal handlers, or it stopped
12    /// because of an I/O error.
13    Serve,
14    /// The builder configuration is incomplete or invalid.
15    InvalidConfig,
16    /// The server received its shutdown signal, and requests or tracked background
17    /// tasks were still running when the grace period ended. The server has cancelled
18    /// its requests by then. Tracked background tasks may still be running.
19    ShutdownTimeout,
20    /// An Identity operation had no workload access token: none was given to the
21    /// operation, and the request context held none or the call ran outside one.
22    MissingWorkloadToken,
23    /// AgentCore Identity answered successfully and returned no API key.
24    NoApiKey,
25    /// AgentCore Identity answered a request for an OAuth2 token with neither a token
26    /// nor an authorization URL.
27    NoTokenOrAuthUrl,
28    /// The application's function for the authorization URL returned an error, which
29    /// is the [`source`](std::error::Error::source).
30    AuthorizationCallbackFailed,
31    /// No OAuth2 token arrived in the time allowed for the user to give consent.
32    AuthorizationTimedOut,
33    /// A call to AgentCore Identity failed. The text of the error names the operation,
34    /// the error code of the service and the request ID, for example
35    /// `GetResourceApiKey failed: AccessDeniedException (request ID: ...)`. A failure
36    /// without a response has the classification of the AWS SDK instead, such as
37    /// `dispatch failure`. [`source`](std::error::Error::source) is the `SdkError` of
38    /// the generated operation.
39    Service,
40}
41
42impl ErrorKind {
43    /// Whether errors of this kind come from the `identity` module. Their source can
44    /// hold a credential.
45    fn is_identity(self) -> bool {
46        matches!(
47            self,
48            Self::MissingWorkloadToken
49                | Self::NoApiKey
50                | Self::NoTokenOrAuthUrl
51                | Self::AuthorizationCallbackFailed
52                | Self::AuthorizationTimedOut
53                | Self::Service
54        )
55    }
56}
57
58/// Error returned by this crate.
59///
60/// Its `Display` text describes this error only. The underlying cause, when there is
61/// one, is available from [`source`](std::error::Error::source) and is not repeated
62/// in the text.
63/// The text of [`ErrorKind::Service`] also has the error code and the request ID of
64/// the failed call, which a log needs to tell failures apart.
65///
66/// # Secrets in the source
67///
68/// The source of an Identity error can hold a credential. For example, the
69/// `SdkError` of a response that could not be decoded keeps the response body, which
70/// can contain the API key, and the error of an application's function for the
71/// authorization URL can contain that URL. The `Debug` output of an Identity error therefore leaves
72/// the source out. The source itself is unchanged: formatting it, or a report that
73/// walks the source chain, can print what it holds.
74pub struct Error {
75    kind: ErrorKind,
76    message: String,
77    source: Option<BoxError>,
78}
79
80impl Error {
81    pub(crate) fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
82        Self { kind, message: message.into(), source: None }
83    }
84
85    #[cfg(any(feature = "runtime", feature = "identity"))]
86    pub(crate) fn with_source(mut self, source: impl Into<BoxError>) -> Self {
87        self.source = Some(source.into());
88        self
89    }
90
91    /// The category of this error.
92    pub fn kind(&self) -> ErrorKind {
93        self.kind
94    }
95
96    /// Whether the source must stay out of the log: the source of an Identity error
97    /// can hold a credential or the authorization URL.
98    #[cfg(feature = "runtime")]
99    pub(crate) fn hides_source(&self) -> bool {
100        self.kind.is_identity()
101    }
102}
103
104impl fmt::Debug for Error {
105    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106        let mut debug = f.debug_struct("Error");
107        debug.field("kind", &self.kind).field("message", &self.message);
108        if self.kind.is_identity() {
109            debug.finish_non_exhaustive()
110        } else {
111            debug.field("source", &self.source).finish()
112        }
113    }
114}
115
116impl fmt::Display for Error {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        f.write_str(&self.message)
119    }
120}
121
122impl std::error::Error for Error {
123    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
124        self.source.as_deref().map(|source| source as _)
125    }
126}
127
128#[cfg(all(test, feature = "runtime"))]
129mod tests {
130    use std::error::Error as _;
131
132    use super::*;
133
134    /// A reporter that prints an error and then its sources must not print the cause twice.
135    #[test]
136    fn display_text_does_not_repeat_the_source() {
137        let cause = std::io::Error::other("address in use");
138        let error = Error::new(ErrorKind::Bind, "failed to bind 127.0.0.1:8080").with_source(cause);
139        assert_eq!(error.to_string(), "failed to bind 127.0.0.1:8080");
140        assert_eq!(error.source().map(ToString::to_string).as_deref(), Some("address in use"));
141    }
142
143    #[test]
144    fn debug_output_of_a_runtime_error_includes_its_source() {
145        let cause = std::io::Error::other("address in use");
146        let error = Error::new(ErrorKind::Bind, "failed to bind").with_source(cause);
147        let debug = format!("{error:?}");
148        assert!(debug.starts_with("Error { kind: Bind, message: \"failed to bind\", source: Some("), "{debug}");
149        assert!(debug.contains("address in use"), "{debug}");
150    }
151}