Skip to main content

rs_matter_utils/
error.rs

1/*
2 *
3 *    Copyright (c) 2022-2026 Project CHIP Authors
4 *
5 *    Licensed under the Apache License, Version 2.0 (the "License");
6 *    you may not use this file except in compliance with the License.
7 *    You may obtain a copy of the License at
8 *
9 *        http://www.apache.org/licenses/LICENSE-2.0
10 *
11 *    Unless required by applicable law or agreed to in writing, software
12 *    distributed under the License is distributed on an "AS IS" BASIS,
13 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 *    See the License for the specific language governing permissions and
15 *    limitations under the License.
16 */
17
18//! The error type of `rs-matter`.
19
20/// The bounds that every error code type must satisfy in order to be used as the
21/// code of an [`Error2`].
22///
23/// Blanket-implemented, so a crate defining its own error code enum only needs the
24/// usual derives - it never implements this trait explicitly.
25#[cfg(not(feature = "defmt"))]
26pub trait MatterError: Copy + core::fmt::Debug {}
27
28#[cfg(not(feature = "defmt"))]
29impl<T> MatterError for T where T: Copy + core::fmt::Debug {}
30
31/// The bounds that every error code type must satisfy in order to be used as the
32/// code of an [`Error2`].
33///
34/// Blanket-implemented, so a crate defining its own error code enum only needs the
35/// usual derives - it never implements this trait explicitly.
36#[cfg(feature = "defmt")]
37pub trait MatterError: Copy + core::fmt::Debug + defmt::Format {}
38
39#[cfg(feature = "defmt")]
40impl<T> MatterError for T where T: Copy + core::fmt::Debug + defmt::Format {}
41
42/// Generic error struct holding any Matter error code and backtrace info.
43pub struct Error2<T> {
44    code: T,
45    #[cfg(all(feature = "std", feature = "backtrace"))]
46    backtrace: std::backtrace::Backtrace,
47    #[cfg(all(feature = "alloc", feature = "backtrace"))]
48    inner: Option<Box<dyn core::error::Error + Send + Sync>>,
49}
50
51impl<T: MatterError> Error2<T> {
52    pub fn new(code: T) -> Self {
53        Self {
54            code,
55            #[cfg(all(feature = "std", feature = "backtrace"))]
56            backtrace: std::backtrace::Backtrace::capture(),
57            #[cfg(all(feature = "alloc", feature = "backtrace"))]
58            inner: None,
59        }
60    }
61
62    #[cfg(all(feature = "alloc", feature = "backtrace"))]
63    pub fn new_with_details(
64        code: T,
65        detailed_err: Box<dyn core::error::Error + Send + Sync>,
66    ) -> Self {
67        Self {
68            code,
69            #[cfg(feature = "std")]
70            backtrace: std::backtrace::Backtrace::capture(),
71            inner: Some(detailed_err),
72        }
73    }
74
75    pub const fn code(&self) -> T {
76        self.code
77    }
78
79    #[cfg(all(feature = "std", feature = "backtrace"))]
80    pub const fn backtrace(&self) -> &std::backtrace::Backtrace {
81        &self.backtrace
82    }
83
84    #[cfg(all(feature = "alloc", feature = "backtrace"))]
85    pub fn details(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
86        self.inner.as_ref().map(|err| err.as_ref())
87    }
88
89    /// Whether a conversion into another error keeps this one as its source.
90    ///
91    /// Not when backtraces are disabled at run time and this error has no source
92    /// of its own: it would add only its code, at the cost of an allocation.
93    #[cfg(all(feature = "alloc", feature = "backtrace"))]
94    fn keep_as_source(&self) -> bool {
95        #[cfg(feature = "std")]
96        {
97            self.inner.is_some()
98                || self.backtrace.status() == std::backtrace::BacktraceStatus::Captured
99        }
100
101        #[cfg(not(feature = "std"))]
102        {
103            true
104        }
105    }
106}
107
108impl<T: MatterError> From<T> for Error2<T> {
109    fn from(value: T) -> Self {
110        Error2::new(value)
111    }
112}
113
114impl<T: MatterError> core::fmt::Debug for Error2<T> {
115    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
116        // TODO: Does this show the error type?
117        write!(f, "Error::{:?}", self.code)?;
118
119        #[cfg(all(feature = "std", feature = "backtrace"))]
120        {
121            if self.backtrace.status() == std::backtrace::BacktraceStatus::Captured {
122                write!(f, "\n{}", self.backtrace)?;
123            }
124        }
125
126        #[cfg(all(feature = "alloc", feature = "backtrace"))]
127        {
128            if let Some(inner) = &self.inner {
129                write!(f, "\nCaused by: {:?}", inner)?;
130            }
131        }
132
133        Ok(())
134    }
135}
136
137impl<T: MatterError> core::fmt::Display for Error2<T> {
138    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
139        #[cfg(all(feature = "alloc", feature = "backtrace"))]
140        {
141            let err_msg = self
142                .inner
143                .as_ref()
144                .map_or(Default::default(), |err| err.to_string());
145
146            if err_msg.is_empty() {
147                write!(f, "{:?}", self.code())
148            } else {
149                write!(f, "{:?}: {}", self.code(), err_msg)
150            }
151        }
152        #[cfg(not(all(feature = "alloc", feature = "backtrace")))]
153        {
154            write!(f, "{:?}", self.code())
155        }
156    }
157}
158
159#[cfg(feature = "defmt")]
160impl<T: MatterError> defmt::Format for Error2<T> {
161    fn format(&self, f: defmt::Formatter<'_>) {
162        defmt::write!(f, "{:?}", self.code())
163    }
164}
165
166impl<T: MatterError> core::error::Error for Error2<T> {
167    #[cfg(all(feature = "alloc", feature = "backtrace"))]
168    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
169        self.inner
170            .as_ref()
171            .map(|e| e.as_ref() as &(dyn core::error::Error + 'static))
172    }
173}
174
175pub type BufferError = Error2<BufferErrorCode>;
176
177/// The errors raised by the byte buffers in [`crate::storage`] - [`crate::storage::WriteBuf`]
178/// and [`crate::storage::ReadBuf`].
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
180#[cfg_attr(feature = "defmt", derive(defmt::Format))]
181pub enum BufferErrorCode {
182    /// A fixed-capacity buffer could not accept the data.
183    BufferTooSmall,
184    /// A read ran past the end of the input.
185    UnexpectedEof,
186}
187
188pub type Base38Error = Error2<Base38ErrorCode>;
189
190/// The errors raised by the base38 codec in [`crate::codec::base38`].
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
192#[cfg_attr(feature = "defmt", derive(defmt::Format))]
193pub enum Base38ErrorCode {
194    /// A character outside the base38 alphabet was encountered while decoding.
195    InvalidCharacter,
196    /// A base38 chunk had a length that cannot encode a whole number of bytes.
197    InvalidLength,
198    /// The caller-supplied output container could not fit the result.
199    OutputTooSmall,
200}
201
202// TODO: Remove these bridges once all dependent crates have been refactored to
203// explicitly handle `BufferError`.
204//
205// `Base38Error` needs no bridge: its only consumer (`rs-matter-pairing`) already
206// converts it explicitly at the call site.
207
208impl From<BufferErrorCode> for ErrorCode {
209    fn from(value: BufferErrorCode) -> Self {
210        match value {
211            BufferErrorCode::BufferTooSmall => ErrorCode::BufferTooSmall,
212            BufferErrorCode::UnexpectedEof => ErrorCode::TruncatedPacket,
213        }
214    }
215}
216
217impl From<BufferErrorCode> for Error {
218    fn from(value: BufferErrorCode) -> Self {
219        ErrorCode::from(value).into()
220    }
221}
222
223/// Bridge any `Error2` to the legacy `Error`, given a conversion for its code.
224///
225/// With `alloc` and `backtrace`, the new error captures its own backtrace and
226/// keeps the `Error2` - with its code and backtrace - as its source, unless
227/// backtraces are disabled at run time (see `Error2::keep_as_source`).
228///
229/// A crate defining its own error code only needs `impl From<ItsCode> for ErrorCode`,
230/// which the orphan rule does allow it - unlike an impl over `Error2<ItsCode>`,
231/// where neither type is local to it.
232impl<T> From<Error2<T>> for Error
233where
234    T: MatterError + Into<ErrorCode> + Send + Sync + 'static,
235{
236    fn from(value: Error2<T>) -> Self {
237        #[cfg(all(feature = "alloc", feature = "backtrace"))]
238        {
239            if value.keep_as_source() {
240                return Self::new_with_details(value.code().into(), Box::new(value));
241            }
242        }
243
244        Self::new(value.code().into())
245    }
246}
247
248// ---
249// TODO: The code below shall be removed after the complete implementation
250// of the error refactor is defined by the `docs/error-refactor-issue-192.md` document.
251
252use core::{array::TryFromSliceError, str::Utf8Error};
253
254#[cfg(all(feature = "alloc", feature = "backtrace"))]
255use alloc::{boxed::Box, string::ToString};
256
257use crate::io;
258
259// TODO: The error code enum is in a need of an overhaul
260//
261// We need separate error enums per chunks of functionality
262// and a way to map them to concrete IM and SC status codes
263//
264// This is a non-trivial effort though as we need to also generify
265// the returned error type of all APIs that take callbacks that return errors
266// (i.e., `Exchange::with_*`, `WriteBuf::append_with_buf` etc.)
267#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
268#[cfg_attr(feature = "defmt", derive(defmt::Format))]
269pub enum ErrorCode {
270    // The codes `TlvErrorCode` maps to come first and in its order, so that
271    // `From<TlvErrorCode> for Error` compiles to nothing.
272    InvalidData,
273    TLVTypeMismatch,
274    NotFound,
275    Invalid,
276    ConstraintError,
277    /// `TlvErrorCode::UnexpectedNull`; reported as a constraint error
278    TLVUnexpectedNull,
279    // TODO: Rename to `TLVNoWriteSpace` or similar, so that it is clear
280    // that this error code should _only_ be used when writing a TLV using
281    // a `TLVWrite` instance which happens to run out of space
282    //
283    // All other cases of running out of space should use the generic:
284    // - `ResourceExhausted` (when number of fabrics, ACLs, sessions or exchanges becomes too big)
285    // - `BufferTooSmall` or `ConstraintError` when other internal buffers don't fit the data
286    // - ... or use-case-specific error codes like `NoSpaceExchanges` and `NoSpaceSessions`.
287    NoSpace,
288    AlreadyExists,
289    AttributeNotFound,
290    AttributeIsCustom,
291    BufferTooSmall,
292    ClusterNotFound,
293    CommandNotFound,
294    Duplicate,
295    NodeNotFound,
296    EndpointNotFound,
297    EventNotFound,
298    InvalidAction,
299    InvalidCommand,
300    FailSafeRequired,
301    NeedsTimedInteraction,
302    DynamicConstraintError,
303    InvalidDataType,
304    UnsupportedAccess,
305    ResourceExhausted,
306    Busy,
307    DataVersionMismatch,
308    BtpError,
309    MdnsError,
310    NoCommand,
311    NoEndpoint,
312    NoExchange,
313    NoFabricId,
314    NoHandler,
315    NoNetworkInterface,
316    DBusError,
317    NoNodeId,
318    NoMemory,
319    NoSession,
320    /// The CASE responder has no fabric and node ID matching our Sigma1, e.g. because it is
321    /// no longer on our fabric, or because it is not the node we asked for.
322    NoSharedTrustRoots,
323    NoSpaceExchanges,
324    NoSpaceSessions,
325    TxTimeout,
326    RxTimeout,
327    NoTagFound,
328    PacketPoolExhaust,
329    StdIoError,
330    SysTimeFail,
331    InvalidAAD,
332    /// An element was received on a transport that cannot carry it - a command
333    /// with the `L` (Large Message) quality over a transport that is not
334    /// large-message capable. Maps to `IMStatusCode::InvalidTransportType`.
335    InvalidTransportType,
336    InvalidKeyLength,
337    InvalidOpcode,
338    InvalidProto,
339    InvalidPeerAddr,
340    // Invalid Auth Key in the Matter Certificate
341    InvalidAuthKey,
342    InvalidSignature,
343    InvalidState,
344    /// The request was well-formed but cannot be carried out in the state
345    /// the resource is in - a fan asked for a speed it cannot switch to right
346    /// now, say. Maps to `IMStatusCode::InvalidInState`, unlike the internal
347    /// `InvalidState`, which is reported as a generic failure.
348    InvalidInState,
349    InvalidTime,
350    InvalidArgument,
351    RwLock,
352    TLVNotFound,
353    TruncatedPacket,
354    Utf8Fail,
355    GennCommInvalidAuthentication,
356    NocInvalidNoc,
357    NocInvalidPublicKey,
358    NocMissingCsr,
359    NocFabricTableFull,
360    NocFabricConflict,
361    NocLabelConflict,
362    NocInvalidFabricIndex,
363    NocInvalidAdminSubject,
364    /// The operation was cancelled by its caller.
365    Cancelled,
366    Failure,
367    // Certification Declaration errors
368    CdInvalidFormat,
369    CdInvalidSignature,
370    CdSigningKeyNotFound,
371    CdInvalidVendorId,
372    CdInvalidProductId,
373    CdInvalidPaa,
374}
375
376impl From<ErrorCode> for Error {
377    fn from(code: ErrorCode) -> Self {
378        Self::new(code)
379    }
380}
381
382pub struct Error {
383    code: ErrorCode,
384    #[cfg(all(feature = "std", feature = "backtrace"))]
385    backtrace: std::backtrace::Backtrace,
386    #[cfg(all(feature = "alloc", feature = "backtrace"))]
387    inner: Option<Box<dyn core::error::Error + Send + Sync>>,
388}
389
390impl Error {
391    pub fn new(code: ErrorCode) -> Self {
392        Self {
393            code,
394            #[cfg(all(feature = "std", feature = "backtrace"))]
395            backtrace: std::backtrace::Backtrace::capture(),
396            #[cfg(all(feature = "alloc", feature = "backtrace"))]
397            inner: None,
398        }
399    }
400
401    #[cfg(all(feature = "alloc", feature = "backtrace"))]
402    pub fn new_with_details(
403        code: ErrorCode,
404        detailed_err: Box<dyn core::error::Error + Send + Sync>,
405    ) -> Self {
406        Self {
407            code,
408            #[cfg(feature = "std")]
409            backtrace: std::backtrace::Backtrace::capture(),
410            inner: Some(detailed_err),
411        }
412    }
413
414    pub const fn code(&self) -> ErrorCode {
415        self.code
416    }
417
418    /// Whether this error means the peer never answered.
419    pub const fn is_peer_unresponsive(&self) -> bool {
420        matches!(self.code, ErrorCode::TxTimeout | ErrorCode::RxTimeout)
421    }
422
423    #[cfg(all(feature = "std", feature = "backtrace"))]
424    pub const fn backtrace(&self) -> &std::backtrace::Backtrace {
425        &self.backtrace
426    }
427
428    #[cfg(all(feature = "alloc", feature = "backtrace"))]
429    pub fn details(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
430        self.inner.as_ref().map(|err| err.as_ref())
431    }
432}
433
434#[cfg(all(feature = "std", feature = "backtrace"))]
435impl From<std::io::Error> for Error {
436    fn from(e: std::io::Error) -> Self {
437        Self::new_with_details(ErrorCode::StdIoError, Box::new(e))
438    }
439}
440
441#[cfg(all(feature = "std", not(feature = "backtrace")))]
442impl From<std::io::Error> for Error {
443    fn from(_e: std::io::Error) -> Self {
444        Self::new(ErrorCode::StdIoError)
445    }
446}
447
448#[cfg(feature = "std")]
449impl<T> From<std::sync::PoisonError<T>> for Error {
450    fn from(_e: std::sync::PoisonError<T>) -> Self {
451        Self::new(ErrorCode::RwLock)
452    }
453}
454
455#[cfg(all(target_os = "linux", feature = "bluer", not(feature = "backtrace")))]
456impl From<bluer::Error> for Error {
457    fn from(e: bluer::Error) -> Self {
458        // Log the error given that we lose all context from the
459        // original error here
460        error!("Error in BTP: {}", display2format!(e));
461        Self::new(ErrorCode::BtpError)
462    }
463}
464
465#[cfg(all(target_os = "linux", feature = "bluer", feature = "backtrace"))]
466impl From<bluer::Error> for Error {
467    fn from(e: bluer::Error) -> Self {
468        Self::new_with_details(ErrorCode::BtpError, Box::new(e))
469    }
470}
471
472#[cfg(all(feature = "zbus", not(feature = "backtrace")))]
473impl From<zbus::Error> for Error {
474    fn from(e: zbus::Error) -> Self {
475        // Log the error given that we lose all context from the
476        // original error here
477        error!("Error in D-Bus: {}", display2format!(e));
478        Self::new(ErrorCode::DBusError)
479    }
480}
481
482#[cfg(all(feature = "zbus", feature = "backtrace"))]
483impl From<zbus::Error> for Error {
484    fn from(e: zbus::Error) -> Self {
485        Self::new_with_details(ErrorCode::DBusError, Box::new(e))
486    }
487}
488
489#[cfg(all(feature = "zbus", not(feature = "backtrace")))]
490impl From<zbus::zvariant::Error> for Error {
491    fn from(e: zbus::zvariant::Error) -> Self {
492        // Log the error given that we lose all context from the
493        // original error here
494        error!("Error in D-Bus: {}", display2format!(e));
495        Self::new(ErrorCode::DBusError)
496    }
497}
498
499#[cfg(all(feature = "zbus", feature = "backtrace"))]
500impl From<zbus::zvariant::Error> for Error {
501    fn from(e: zbus::zvariant::Error) -> Self {
502        Self::new_with_details(ErrorCode::DBusError, Box::new(e))
503    }
504}
505
506#[cfg(all(feature = "zbus", not(feature = "backtrace")))]
507impl From<zbus::fdo::Error> for Error {
508    fn from(e: zbus::fdo::Error) -> Self {
509        // Log the error given that we lose all context from the
510        // original error here
511        error!("Error in D-Bus: {}", display2format!(e));
512        Self::new(ErrorCode::DBusError)
513    }
514}
515
516#[cfg(all(feature = "zbus", feature = "backtrace"))]
517impl From<zbus::fdo::Error> for Error {
518    fn from(e: zbus::fdo::Error) -> Self {
519        Self::new_with_details(ErrorCode::DBusError, Box::new(e))
520    }
521}
522
523#[cfg(feature = "std")]
524impl From<std::time::SystemTimeError> for Error {
525    fn from(_e: std::time::SystemTimeError) -> Self {
526        Error::new(ErrorCode::SysTimeFail)
527    }
528}
529
530impl From<TryFromSliceError> for Error {
531    fn from(_e: TryFromSliceError) -> Self {
532        Self::new(ErrorCode::Invalid)
533    }
534}
535
536impl From<Utf8Error> for Error {
537    fn from(_e: Utf8Error) -> Self {
538        Self::new(ErrorCode::Utf8Fail)
539    }
540}
541
542impl<T: num_enum::TryFromPrimitive> From<num_enum::TryFromPrimitiveError<T>> for Error {
543    fn from(_e: num_enum::TryFromPrimitiveError<T>) -> Self {
544        Self::new(ErrorCode::Invalid)
545    }
546}
547
548impl core::fmt::Debug for Error {
549    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
550        write!(f, "Error::{:?}", self.code)?;
551
552        #[cfg(all(feature = "std", feature = "backtrace"))]
553        {
554            if self.backtrace.status() == std::backtrace::BacktraceStatus::Captured {
555                write!(f, "\n{}", self.backtrace)?;
556            }
557        }
558
559        #[cfg(all(feature = "alloc", feature = "backtrace"))]
560        {
561            if let Some(inner) = &self.inner {
562                write!(f, "\nCaused by: {:?}", inner)?;
563            }
564        }
565
566        Ok(())
567    }
568}
569
570impl core::fmt::Display for Error {
571    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
572        #[cfg(all(feature = "alloc", feature = "backtrace"))]
573        {
574            let err_msg = self
575                .inner
576                .as_ref()
577                .map_or(Default::default(), |err| err.to_string());
578
579            if err_msg.is_empty() {
580                write!(f, "{:?}", self.code())
581            } else {
582                write!(f, "{:?}: {}", self.code(), err_msg)
583            }
584        }
585        #[cfg(not(all(feature = "alloc", feature = "backtrace")))]
586        {
587            write!(f, "{:?}", self.code())
588        }
589    }
590}
591
592#[cfg(feature = "defmt")]
593impl defmt::Format for Error {
594    fn format(&self, f: defmt::Formatter<'_>) {
595        defmt::write!(f, "{:?}", self.code())
596    }
597}
598
599impl core::error::Error for Error {
600    #[cfg(all(feature = "alloc", feature = "backtrace"))]
601    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
602        self.inner
603            .as_ref()
604            .map(|e| e.as_ref() as &(dyn core::error::Error + 'static))
605    }
606}
607
608impl io::Error for Error {
609    fn kind(&self) -> io::ErrorKind {
610        io::ErrorKind::Other
611    }
612}
613
614#[cfg(test)]
615#[cfg_attr(coverage_nightly, coverage(off))]
616mod tests {
617    use core::str::from_utf8;
618
619    use super::{Error, ErrorCode};
620
621    /// A representative slice of the error codes, covering the first and last
622    /// variants and the ones with special `From` mappings.
623    const CODES: &[ErrorCode] = &[
624        ErrorCode::AlreadyExists,
625        ErrorCode::AttributeNotFound,
626        ErrorCode::BufferTooSmall,
627        ErrorCode::ConstraintError,
628        ErrorCode::Invalid,
629        ErrorCode::InvalidData,
630        ErrorCode::InvalidTransportType,
631        ErrorCode::NoSpace,
632        ErrorCode::TxTimeout,
633        ErrorCode::RxTimeout,
634        ErrorCode::StdIoError,
635        ErrorCode::SysTimeFail,
636        ErrorCode::RwLock,
637        ErrorCode::Utf8Fail,
638        ErrorCode::Failure,
639        ErrorCode::CdInvalidPaa,
640    ];
641
642    #[test]
643    fn code_roundtrips_through_error() {
644        for code in CODES {
645            let err = Error::new(*code);
646            assert_eq!(err.code(), *code);
647
648            let err: Error = (*code).into();
649            assert_eq!(err.code(), *code);
650
651            // `?` on an `ErrorCode` works via the same `From`
652            let res: Result<(), Error> = (|| {
653                Err(*code)?;
654                Ok(())
655            })();
656            assert_eq!(res.unwrap_err().code(), *code);
657        }
658    }
659
660    #[test]
661    fn error_code_equality_and_hash() {
662        use std::collections::HashSet;
663
664        assert_eq!(ErrorCode::NoSpace, ErrorCode::NoSpace);
665        assert_ne!(ErrorCode::NoSpace, ErrorCode::NoSpaceExchanges);
666
667        let set: HashSet<ErrorCode> = CODES.iter().copied().collect();
668        assert_eq!(set.len(), CODES.len());
669
670        // Copy semantics
671        let a = ErrorCode::Busy;
672        let b = a;
673        assert_eq!(a, b);
674    }
675
676    #[test]
677    fn display_and_debug_do_not_panic() {
678        for code in CODES {
679            let err = Error::new(*code);
680
681            let display = format!("{err}");
682            let debug = format!("{err:?}");
683            let code_debug = format!("{code:?}");
684
685            // Display is the code's Debug name; Debug wraps it as `Error::<name>`
686            assert!(
687                display.starts_with(&code_debug),
688                "{display} vs {code_debug}"
689            );
690            assert!(
691                debug.starts_with(&format!("Error::{code_debug}")),
692                "{debug}"
693            );
694        }
695    }
696
697    #[test]
698    fn is_peer_unresponsive_only_for_timeouts() {
699        assert!(Error::new(ErrorCode::TxTimeout).is_peer_unresponsive());
700        assert!(Error::new(ErrorCode::RxTimeout).is_peer_unresponsive());
701
702        for code in CODES {
703            if !matches!(code, ErrorCode::TxTimeout | ErrorCode::RxTimeout) {
704                assert!(!Error::new(*code).is_peer_unresponsive(), "{code:?}");
705            }
706        }
707    }
708
709    #[test]
710    fn core_conversions() {
711        let slice_err = <[u8; 4]>::try_from(&[1u8, 2, 3][..]).unwrap_err();
712        assert_eq!(Error::from(slice_err).code(), ErrorCode::Invalid);
713
714        // Built at runtime so the lint does not flag a constant-invalid literal
715        let invalid: Vec<u8> = (0..2).map(|i| 0xff - i as u8).collect();
716        let utf8_err = from_utf8(&invalid).unwrap_err();
717        assert_eq!(Error::from(utf8_err).code(), ErrorCode::Utf8Fail);
718
719        #[derive(Debug, Copy, Clone, num_enum::TryFromPrimitive)]
720        #[repr(u8)]
721        enum Small {
722            _One = 1,
723        }
724        let prim_err = Small::try_from(9u8).unwrap_err();
725        assert_eq!(Error::from(prim_err).code(), ErrorCode::Invalid);
726    }
727
728    #[test]
729    fn error_is_a_core_error() {
730        let err = Error::new(ErrorCode::Busy);
731        let dyn_err: &dyn core::error::Error = &err;
732
733        // Without details attached there is no source
734        assert!(dyn_err.source().is_none());
735
736        // `?` from an `Error` into a boxed error works
737        let boxed: Box<dyn core::error::Error + Send + Sync> = Box::new(err);
738        assert!(boxed.to_string().contains("Busy"));
739    }
740
741    #[test]
742    fn embedded_io_error_kind_is_other() {
743        use embedded_io_async::{Error as _, ErrorKind};
744
745        assert_eq!(Error::new(ErrorCode::NoSpace).kind(), ErrorKind::Other);
746    }
747
748    #[cfg(feature = "std")]
749    #[test]
750    fn std_conversions() {
751        let io = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
752        let err = Error::from(io);
753        assert_eq!(err.code(), ErrorCode::StdIoError);
754
755        let lock = std::sync::Mutex::new(());
756        let poisoned = std::sync::PoisonError::new(lock.lock().unwrap());
757        assert_eq!(Error::from(poisoned).code(), ErrorCode::RwLock);
758
759        let time_err = std::time::UNIX_EPOCH
760            .duration_since(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1))
761            .unwrap_err();
762        assert_eq!(Error::from(time_err).code(), ErrorCode::SysTimeFail);
763    }
764
765    #[cfg(all(feature = "alloc", feature = "backtrace"))]
766    #[test]
767    fn details_are_kept_and_displayed() {
768        let err = Error::new(ErrorCode::Busy);
769        assert!(err.details().is_none());
770        assert_eq!(format!("{err}"), "Busy");
771
772        let inner = std::io::Error::other("disk on fire");
773        let err = Error::new_with_details(ErrorCode::StdIoError, Box::new(inner));
774        assert_eq!(err.code(), ErrorCode::StdIoError);
775        assert!(err.details().unwrap().to_string().contains("disk on fire"));
776        assert_eq!(format!("{err}"), "StdIoError: disk on fire");
777
778        // The details are exposed as the `source`
779        let dyn_err: &dyn core::error::Error = &err;
780        assert!(dyn_err
781            .source()
782            .unwrap()
783            .to_string()
784            .contains("disk on fire"));
785
786        // `From<std::io::Error>` also attaches the details under `backtrace`
787        #[cfg(feature = "std")]
788        {
789            let io = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
790            let err = Error::from(io);
791            assert!(err.details().unwrap().to_string().contains("gone"));
792        }
793    }
794
795    #[cfg(all(feature = "std", feature = "backtrace"))]
796    #[test]
797    fn backtrace_capture_does_not_panic() {
798        let err = Error::new(ErrorCode::Failure);
799
800        // Capture may be disabled by the environment; only its presence is checked
801        let _ = err.backtrace().status();
802        let _ = format!("{}", err.backtrace());
803
804        // Debug shows the code, then the backtrace if one was captured
805        let debug = format!("{err:?}");
806        assert!(debug.starts_with("Error::Failure"));
807        if err.backtrace().status() != std::backtrace::BacktraceStatus::Captured {
808            assert_eq!(debug, "Error::Failure");
809        }
810    }
811
812    #[cfg(all(feature = "alloc", feature = "backtrace"))]
813    #[test]
814    fn converted_error_is_kept_as_source() {
815        use super::{BufferError, BufferErrorCode};
816
817        // An error with a source of its own is always kept
818        let err = Error::from(BufferError::new_with_details(
819            BufferErrorCode::UnexpectedEof,
820            Box::new(std::io::Error::other("short read")),
821        ));
822        assert_eq!(err.code(), ErrorCode::TruncatedPacket);
823
824        let source = core::error::Error::source(&err).unwrap();
825        let source = source.downcast_ref::<BufferError>().unwrap();
826        assert_eq!(source.code(), BufferErrorCode::UnexpectedEof);
827
828        assert_eq!(
829            format!("{err}"),
830            "TruncatedPacket: UnexpectedEof: short read"
831        );
832
833        let debug = format!("{err:?}");
834        assert!(debug.starts_with("Error::TruncatedPacket"));
835        assert!(debug.contains("\nCaused by: Error::UnexpectedEof"));
836        assert!(debug.contains("short read"));
837
838        // Otherwise only when backtraces are enabled at run time
839        #[cfg(feature = "std")]
840        {
841            let source = BufferError::new(BufferErrorCode::UnexpectedEof);
842            let captured = source.backtrace().status() == std::backtrace::BacktraceStatus::Captured;
843
844            assert_eq!(Error::from(source).details().is_some(), captured);
845        }
846    }
847
848    #[cfg(all(feature = "alloc", feature = "backtrace"))]
849    #[test]
850    fn details_can_be_downcast() {
851        use super::{BufferError, BufferErrorCode};
852
853        let err = Error::from(BufferError::new_with_details(
854            BufferErrorCode::UnexpectedEof,
855            Box::new(std::io::Error::other("short read")),
856        ));
857
858        // `Error::details` is the converted `Error2`, and its `details` the I/O error
859        let source = err.details().unwrap().downcast_ref::<BufferError>();
860        let source = source.unwrap();
861        assert_eq!(source.code(), BufferErrorCode::UnexpectedEof);
862
863        let io = source.details().unwrap().downcast_ref::<std::io::Error>();
864        assert_eq!(io.unwrap().to_string(), "short read");
865    }
866}