Skip to main content

ntex_error/
lib.rs

1//! Error management.
2#![deny(clippy::pedantic)]
3#![allow(
4    clippy::must_use_candidate,
5    clippy::missing_errors_doc,
6    clippy::missing_panics_doc
7)]
8use std::{error::Error as StdError, fmt};
9
10use ntex_bytes::Bytes;
11
12mod bt;
13mod chain;
14mod error;
15mod ext;
16mod info;
17mod message;
18mod repr;
19pub mod utils;
20
21pub use crate::bt::{Backtrace, BacktraceResolver};
22pub use crate::chain::ErrorChain;
23pub use crate::error::Error;
24pub use crate::info::ErrorInfo;
25pub use crate::message::{ErrorMessage, ErrorMessageChained};
26pub use crate::message::{fmt_diag, fmt_diag_string, fmt_err, fmt_err_string};
27pub use crate::utils::{Success, with_service};
28
29#[doc(hidden)]
30pub use crate::bt::{set_backtrace_start, set_backtrace_start_alt};
31
32/// The type of the result.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub enum ResultType {
35    Success,
36    ClientError,
37    ServiceError,
38}
39
40impl ResultType {
41    /// Returns a str representation of the result type.
42    pub const fn as_str(&self) -> &'static str {
43        match self {
44            ResultType::Success => "Success",
45            ResultType::ClientError => "ClientError",
46            ResultType::ServiceError => "ServiceError",
47        }
48    }
49}
50
51/// Describes how a domain-specific error maps into a unified result model.
52pub trait ResultKind: 'static {
53    /// Returns the classification of the result (e.g. success, client error, service error).
54    fn tp(&self) -> ResultType;
55
56    /// Returns a stable identifier for the specific error classification.
57    ///
58    /// It is used for logging, metrics, and diagnostics.
59    fn signature(&self) -> &'static str;
60}
61
62impl ResultKind for ResultType {
63    fn tp(&self) -> ResultType {
64        *self
65    }
66
67    fn signature(&self) -> &'static str {
68        self.as_str()
69    }
70}
71
72/// Provides diagnostic information for errors.
73///
74/// It enables classification, service attribution, and debugging context.
75pub trait ErrorDiagnostic: StdError + 'static {
76    type Kind: ResultKind;
77
78    /// Returns the classification kind of this error.
79    fn kind(&self) -> Self::Kind;
80
81    /// Returns an optional tag associated with this error.
82    ///
83    /// The tag is user-defined and can be used for additional classification
84    /// or correlation.
85    fn tag(&self) -> Option<&Bytes> {
86        None
87    }
88
89    /// Returns the name of the responsible service, if applicable.
90    ///
91    /// Used to identify upstream or internal service ownership for diagnostics.
92    fn service(&self) -> Option<&'static str> {
93        None
94    }
95
96    /// Returns a backtrace for debugging purposes, if available.
97    fn backtrace(&self) -> Option<&Backtrace> {
98        None
99    }
100
101    #[track_caller]
102    fn chain(self) -> ErrorChain<Self::Kind>
103    where
104        Self: Sized,
105    {
106        ErrorChain::new(self)
107    }
108}
109
110/// Helper trait for converting a value into a unified error-aware result type.
111pub trait ErrorMapping<T, E, U> {
112    /// Converts the value into a `Result`, wrapping it in a structured error type if needed.
113    fn into_error(self) -> Result<T, Error<U>>;
114}
115
116impl fmt::Display for ResultType {
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        write!(f, "{}", self.as_str())
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use std::{error::Error as StdError, io, mem};
125
126    use super::*;
127
128    #[derive(Copy, Clone, Debug, PartialEq, Eq, thiserror::Error)]
129    enum TestKind {
130        #[error("Connect")]
131        Connect,
132        #[error("Disconnect")]
133        Disconnect,
134        #[error("ServiceError")]
135        ServiceError,
136    }
137
138    impl ResultKind for TestKind {
139        fn tp(&self) -> ResultType {
140            match self {
141                TestKind::Connect | TestKind::Disconnect => ResultType::ClientError,
142                TestKind::ServiceError => ResultType::ServiceError,
143            }
144        }
145
146        fn signature(&self) -> &'static str {
147            match self {
148                TestKind::Connect => "Client-Connect",
149                TestKind::Disconnect => "Client-Disconnect",
150                TestKind::ServiceError => "Service-Internal",
151            }
152        }
153    }
154
155    #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
156    enum TestError {
157        #[error("Connect err: {0}")]
158        Connect(&'static str),
159        #[error("Disconnect")]
160        Disconnect,
161        #[error("InternalServiceError")]
162        Service(&'static str),
163    }
164
165    impl ErrorDiagnostic for TestError {
166        type Kind = TestKind;
167
168        fn kind(&self) -> Self::Kind {
169            match self {
170                TestError::Connect(_) => TestKind::Connect,
171                TestError::Disconnect => TestKind::Disconnect,
172                TestError::Service(_) => TestKind::ServiceError,
173            }
174        }
175
176        fn service(&self) -> Option<&'static str> {
177            Some("test")
178        }
179    }
180
181    #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
182    #[error("TestError2")]
183    struct TestError2;
184    impl ErrorDiagnostic for TestError2 {
185        type Kind = ResultType;
186
187        fn kind(&self) -> Self::Kind {
188            ResultType::ClientError
189        }
190    }
191
192    impl From<TestError> for TestError2 {
193        fn from(_err: TestError) -> TestError2 {
194            TestError2
195        }
196    }
197
198    #[ntex::test]
199    async fn test_error() {
200        let err: Error<TestError> = TestError::Service("409 Error").into();
201        let err = err.clone();
202        assert_eq!(err.kind(), TestKind::ServiceError);
203        assert_eq!((*err).kind(), TestKind::ServiceError);
204        assert_eq!(err.to_string(), "InternalServiceError");
205        assert_eq!(err.service(), Some("test"));
206        assert_eq!(err.kind().signature(), "Service-Internal");
207        assert_eq!(
208            err,
209            Into::<Error<TestError>>::into(TestError::Service("409 Error"))
210        );
211        assert!(err.backtrace().is_some());
212
213        let err = err.set_service("SVC");
214        assert_eq!(err.service(), Some("SVC"));
215        let err = err.set_tag("TAG");
216        assert_eq!(err.tag().unwrap(), &b"TAG"[..]);
217
218        let err2: Error<TestError> = Error::new(TestError::Service("409 Error"), "TEST");
219        assert!(err != err2);
220        assert_eq!(err, TestError::Service("409 Error"));
221
222        let err2 = err2.set_tag("TAG");
223        assert_eq!(err.tag().unwrap(), &b"TAG"[..]);
224        let err2 = err2.set_service("SVC");
225        assert_eq!(err, err2);
226        let err2 = err2.map(|_| TestError::Disconnect);
227        assert!(err != err2);
228        let err2 = err2.forward(|_| TestError::Disconnect);
229        assert!(err != err2);
230
231        assert_eq!(TestError::Connect("").kind().tp(), ResultType::ClientError);
232        assert_eq!(TestError::Disconnect.kind().tp(), ResultType::ClientError);
233        assert_eq!(TestError::Service("").kind().tp(), ResultType::ServiceError);
234        assert_eq!(TestError::Connect("").to_string(), "Connect err: ");
235        assert_eq!(TestError::Disconnect.to_string(), "Disconnect");
236        assert_eq!(TestError::Disconnect.service(), Some("test"));
237        assert!(TestError::Disconnect.backtrace().is_none());
238
239        assert_eq!(ResultType::ClientError.as_str(), "ClientError");
240        assert_eq!(ResultType::ServiceError.as_str(), "ServiceError");
241        assert_eq!(ResultType::ClientError.tp(), ResultType::ClientError);
242        assert_eq!(ResultType::ServiceError.tp(), ResultType::ServiceError);
243        assert_eq!(ResultType::ClientError.to_string(), "ClientError");
244        assert_eq!(ResultType::ServiceError.to_string(), "ServiceError");
245        assert_eq!(format!("{}", ResultType::ClientError), "ClientError");
246
247        assert_eq!(TestKind::Connect.to_string(), "Connect");
248        assert_eq!(TestError::Connect("").kind().signature(), "Client-Connect");
249        assert_eq!(TestKind::Disconnect.to_string(), "Disconnect");
250        assert_eq!(
251            TestError::Disconnect.kind().signature(),
252            "Client-Disconnect"
253        );
254        assert_eq!(TestKind::ServiceError.to_string(), "ServiceError");
255        assert_eq!(
256            TestError::Service("").kind().signature(),
257            "Service-Internal"
258        );
259
260        let err = err.into_error().chain();
261        assert_eq!(err.kind(), TestKind::ServiceError);
262        assert_eq!(err.kind(), TestError::Service("409 Error").kind());
263        assert_eq!(err.to_string(), "InternalServiceError");
264        assert!(format!("{err:?}").contains("Service(\"409 Error\")"));
265        assert!(
266            format!("{:?}", err.source()).contains("Service(\"409 Error\")"),
267            "{:?}",
268            err.source().unwrap()
269        );
270
271        let err: Error<TestError> = TestError::Service("404 Error").into();
272        #[cfg(unix)]
273        {
274            if let Some(bt) = err.backtrace() {
275                bt.resolver().resolve();
276                assert!(
277                    format!("{bt}").contains("ntex_error::tests::test_error"),
278                    "{bt}",
279                );
280                assert!(
281                    bt.repr().unwrap().contains("ntex_error::tests::test_error"),
282                    "{bt}"
283                );
284            }
285        }
286
287        let err: ErrorChain<TestKind> = err.into();
288        assert_eq!(err.kind(), TestKind::ServiceError);
289        assert_eq!(err.kind(), TestError::Service("404 Error").kind());
290        assert_eq!(err.service(), Some("test"));
291        assert_eq!(err.kind().signature(), "Service-Internal");
292        assert_eq!(err.to_string(), "InternalServiceError");
293        assert!(err.backtrace().is_some());
294        assert!(format!("{err:?}").contains("Service(\"404 Error\")"));
295
296        assert_eq!(24, mem::size_of::<TestError>());
297        assert_eq!(8, mem::size_of::<Error<TestError>>());
298
299        assert_eq!(TestError2.service(), None);
300        assert_eq!(TestError2.kind().signature(), "ClientError");
301
302        // ErrorInformation
303        let err: Error<TestError> = TestError::Service("409 Error").into();
304        let msg = fmt_err_string(&err);
305        assert_eq!(msg, "InternalServiceError\n");
306        let msg = fmt_diag_string(&err);
307        assert!(msg.contains("err: InternalServiceError"));
308
309        let err: ErrorInfo = err.set_service("SVC").into();
310        assert_eq!(err.tp(), ResultType::ServiceError);
311        assert_eq!(err.service(), Some("SVC"));
312        assert_eq!(err.signature(), "Service-Internal");
313        assert!(err.backtrace().is_some());
314
315        let res = Err(TestError::Service("409 Error"));
316        let res: Result<(), Error<TestError>> = res.into_error();
317        let _res: Result<(), Error<TestError2>> = res.into_error();
318
319        let msg = fmt_err_string(&err);
320        assert_eq!(msg, "InternalServiceError\n");
321        let msg = fmt_diag_string(&err);
322        assert!(msg.contains("err: InternalServiceError"));
323
324        // Error extensions
325        let err: Error<TestError> = TestError::Service("409 Error").into();
326        assert_eq!(err.get_item::<&str>(), None);
327        let err = err.insert_item("Test");
328        assert_eq!(err.get_item::<&str>(), Some(&"Test"));
329        let err2 = err.clone();
330        assert_eq!(err2.get_item::<&str>(), Some(&"Test"));
331        let err2 = err2.insert_item("Test2");
332        assert_eq!(err2.get_item::<&str>(), Some(&"Test2"));
333        assert_eq!(err.get_item::<&str>(), Some(&"Test"));
334        let err2 = err.clone().map(|_| TestError::Disconnect);
335        assert_eq!(err2.get_item::<&str>(), Some(&"Test"));
336
337        let info = ErrorInfo::from(&err2);
338        assert_eq!(info.get_item::<&str>(), Some(&"Test"));
339
340        let err3 = err
341            .clone()
342            .try_map(|_| Err::<(), _>(TestError2))
343            .err()
344            .unwrap();
345        assert_eq!(err3.kind().signature(), "ClientError");
346        assert_eq!(err3.get_item::<&str>(), Some(&"Test"));
347
348        let res = err.clone().try_map(|_| Ok::<_, TestError2>(()));
349        assert_eq!(res, Ok(()));
350
351        assert_eq!(Success.kind(), ResultType::Success);
352        assert_eq!(format!("{Success}"), "Success");
353
354        assert_eq!(
355            ErrorDiagnostic::kind(&io::Error::other("")),
356            ResultType::ServiceError
357        );
358        assert_eq!(
359            ErrorDiagnostic::kind(&io::Error::new(io::ErrorKind::InvalidData, "")),
360            ResultType::ClientError
361        );
362    }
363}