#[cfg(not(feature = "defmt"))]
pub trait MatterError: Copy + core::fmt::Debug {}
#[cfg(not(feature = "defmt"))]
impl<T> MatterError for T where T: Copy + core::fmt::Debug {}
#[cfg(feature = "defmt")]
pub trait MatterError: Copy + core::fmt::Debug + defmt::Format {}
#[cfg(feature = "defmt")]
impl<T> MatterError for T where T: Copy + core::fmt::Debug + defmt::Format {}
pub struct Error2<T> {
code: T,
#[cfg(all(feature = "std", feature = "backtrace"))]
backtrace: std::backtrace::Backtrace,
#[cfg(all(feature = "alloc", feature = "backtrace"))]
inner: Option<Box<dyn core::error::Error + Send + Sync>>,
}
impl<T: MatterError> Error2<T> {
pub fn new(code: T) -> Self {
Self {
code,
#[cfg(all(feature = "std", feature = "backtrace"))]
backtrace: std::backtrace::Backtrace::capture(),
#[cfg(all(feature = "alloc", feature = "backtrace"))]
inner: None,
}
}
#[cfg(all(feature = "alloc", feature = "backtrace"))]
pub fn new_with_details(
code: T,
detailed_err: Box<dyn core::error::Error + Send + Sync>,
) -> Self {
Self {
code,
#[cfg(feature = "std")]
backtrace: std::backtrace::Backtrace::capture(),
inner: Some(detailed_err),
}
}
pub const fn code(&self) -> T {
self.code
}
#[cfg(all(feature = "std", feature = "backtrace"))]
pub const fn backtrace(&self) -> &std::backtrace::Backtrace {
&self.backtrace
}
#[cfg(all(feature = "alloc", feature = "backtrace"))]
pub fn details(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
self.inner.as_ref().map(|err| err.as_ref())
}
#[cfg(all(feature = "alloc", feature = "backtrace"))]
fn keep_as_source(&self) -> bool {
#[cfg(feature = "std")]
{
self.inner.is_some()
|| self.backtrace.status() == std::backtrace::BacktraceStatus::Captured
}
#[cfg(not(feature = "std"))]
{
true
}
}
}
impl<T: MatterError> From<T> for Error2<T> {
fn from(value: T) -> Self {
Error2::new(value)
}
}
impl<T: MatterError> core::fmt::Debug for Error2<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Error::{:?}", self.code)?;
#[cfg(all(feature = "std", feature = "backtrace"))]
{
if self.backtrace.status() == std::backtrace::BacktraceStatus::Captured {
write!(f, "\n{}", self.backtrace)?;
}
}
#[cfg(all(feature = "alloc", feature = "backtrace"))]
{
if let Some(inner) = &self.inner {
write!(f, "\nCaused by: {:?}", inner)?;
}
}
Ok(())
}
}
impl<T: MatterError> core::fmt::Display for Error2<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
#[cfg(all(feature = "alloc", feature = "backtrace"))]
{
let err_msg = self
.inner
.as_ref()
.map_or(Default::default(), |err| err.to_string());
if err_msg.is_empty() {
write!(f, "{:?}", self.code())
} else {
write!(f, "{:?}: {}", self.code(), err_msg)
}
}
#[cfg(not(all(feature = "alloc", feature = "backtrace")))]
{
write!(f, "{:?}", self.code())
}
}
}
#[cfg(feature = "defmt")]
impl<T: MatterError> defmt::Format for Error2<T> {
fn format(&self, f: defmt::Formatter<'_>) {
defmt::write!(f, "{:?}", self.code())
}
}
impl<T: MatterError> core::error::Error for Error2<T> {
#[cfg(all(feature = "alloc", feature = "backtrace"))]
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
self.inner
.as_ref()
.map(|e| e.as_ref() as &(dyn core::error::Error + 'static))
}
}
pub type BufferError = Error2<BufferErrorCode>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum BufferErrorCode {
BufferTooSmall,
UnexpectedEof,
}
pub type Base38Error = Error2<Base38ErrorCode>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Base38ErrorCode {
InvalidCharacter,
InvalidLength,
OutputTooSmall,
}
impl From<BufferErrorCode> for ErrorCode {
fn from(value: BufferErrorCode) -> Self {
match value {
BufferErrorCode::BufferTooSmall => ErrorCode::BufferTooSmall,
BufferErrorCode::UnexpectedEof => ErrorCode::TruncatedPacket,
}
}
}
impl From<BufferErrorCode> for Error {
fn from(value: BufferErrorCode) -> Self {
ErrorCode::from(value).into()
}
}
impl<T> From<Error2<T>> for Error
where
T: MatterError + Into<ErrorCode> + Send + Sync + 'static,
{
fn from(value: Error2<T>) -> Self {
#[cfg(all(feature = "alloc", feature = "backtrace"))]
{
if value.keep_as_source() {
return Self::new_with_details(value.code().into(), Box::new(value));
}
}
Self::new(value.code().into())
}
}
use core::{array::TryFromSliceError, str::Utf8Error};
#[cfg(all(feature = "alloc", feature = "backtrace"))]
use alloc::{boxed::Box, string::ToString};
use crate::io;
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ErrorCode {
InvalidData,
TLVTypeMismatch,
NotFound,
Invalid,
ConstraintError,
TLVUnexpectedNull,
NoSpace,
AlreadyExists,
AttributeNotFound,
AttributeIsCustom,
BufferTooSmall,
ClusterNotFound,
CommandNotFound,
Duplicate,
NodeNotFound,
EndpointNotFound,
EventNotFound,
InvalidAction,
InvalidCommand,
FailSafeRequired,
NeedsTimedInteraction,
DynamicConstraintError,
InvalidDataType,
UnsupportedAccess,
ResourceExhausted,
Busy,
DataVersionMismatch,
BtpError,
MdnsError,
NoCommand,
NoEndpoint,
NoExchange,
NoFabricId,
NoHandler,
NoNetworkInterface,
DBusError,
NoNodeId,
NoMemory,
NoSession,
NoSharedTrustRoots,
NoSpaceExchanges,
NoSpaceSessions,
TxTimeout,
RxTimeout,
NoTagFound,
PacketPoolExhaust,
StdIoError,
SysTimeFail,
InvalidAAD,
InvalidTransportType,
InvalidKeyLength,
InvalidOpcode,
InvalidProto,
InvalidPeerAddr,
InvalidAuthKey,
InvalidSignature,
InvalidState,
InvalidInState,
InvalidTime,
InvalidArgument,
RwLock,
TLVNotFound,
TruncatedPacket,
Utf8Fail,
GennCommInvalidAuthentication,
NocInvalidNoc,
NocInvalidPublicKey,
NocMissingCsr,
NocFabricTableFull,
NocFabricConflict,
NocLabelConflict,
NocInvalidFabricIndex,
NocInvalidAdminSubject,
Cancelled,
Failure,
CdInvalidFormat,
CdInvalidSignature,
CdSigningKeyNotFound,
CdInvalidVendorId,
CdInvalidProductId,
CdInvalidPaa,
}
impl From<ErrorCode> for Error {
fn from(code: ErrorCode) -> Self {
Self::new(code)
}
}
pub struct Error {
code: ErrorCode,
#[cfg(all(feature = "std", feature = "backtrace"))]
backtrace: std::backtrace::Backtrace,
#[cfg(all(feature = "alloc", feature = "backtrace"))]
inner: Option<Box<dyn core::error::Error + Send + Sync>>,
}
impl Error {
pub fn new(code: ErrorCode) -> Self {
Self {
code,
#[cfg(all(feature = "std", feature = "backtrace"))]
backtrace: std::backtrace::Backtrace::capture(),
#[cfg(all(feature = "alloc", feature = "backtrace"))]
inner: None,
}
}
#[cfg(all(feature = "alloc", feature = "backtrace"))]
pub fn new_with_details(
code: ErrorCode,
detailed_err: Box<dyn core::error::Error + Send + Sync>,
) -> Self {
Self {
code,
#[cfg(feature = "std")]
backtrace: std::backtrace::Backtrace::capture(),
inner: Some(detailed_err),
}
}
pub const fn code(&self) -> ErrorCode {
self.code
}
pub const fn is_peer_unresponsive(&self) -> bool {
matches!(self.code, ErrorCode::TxTimeout | ErrorCode::RxTimeout)
}
#[cfg(all(feature = "std", feature = "backtrace"))]
pub const fn backtrace(&self) -> &std::backtrace::Backtrace {
&self.backtrace
}
#[cfg(all(feature = "alloc", feature = "backtrace"))]
pub fn details(&self) -> Option<&(dyn core::error::Error + Send + Sync + 'static)> {
self.inner.as_ref().map(|err| err.as_ref())
}
}
#[cfg(all(feature = "std", feature = "backtrace"))]
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Self::new_with_details(ErrorCode::StdIoError, Box::new(e))
}
}
#[cfg(all(feature = "std", not(feature = "backtrace")))]
impl From<std::io::Error> for Error {
fn from(_e: std::io::Error) -> Self {
Self::new(ErrorCode::StdIoError)
}
}
#[cfg(feature = "std")]
impl<T> From<std::sync::PoisonError<T>> for Error {
fn from(_e: std::sync::PoisonError<T>) -> Self {
Self::new(ErrorCode::RwLock)
}
}
#[cfg(all(target_os = "linux", feature = "bluer", not(feature = "backtrace")))]
impl From<bluer::Error> for Error {
fn from(e: bluer::Error) -> Self {
error!("Error in BTP: {}", display2format!(e));
Self::new(ErrorCode::BtpError)
}
}
#[cfg(all(target_os = "linux", feature = "bluer", feature = "backtrace"))]
impl From<bluer::Error> for Error {
fn from(e: bluer::Error) -> Self {
Self::new_with_details(ErrorCode::BtpError, Box::new(e))
}
}
#[cfg(all(feature = "zbus", not(feature = "backtrace")))]
impl From<zbus::Error> for Error {
fn from(e: zbus::Error) -> Self {
error!("Error in D-Bus: {}", display2format!(e));
Self::new(ErrorCode::DBusError)
}
}
#[cfg(all(feature = "zbus", feature = "backtrace"))]
impl From<zbus::Error> for Error {
fn from(e: zbus::Error) -> Self {
Self::new_with_details(ErrorCode::DBusError, Box::new(e))
}
}
#[cfg(all(feature = "zbus", not(feature = "backtrace")))]
impl From<zbus::zvariant::Error> for Error {
fn from(e: zbus::zvariant::Error) -> Self {
error!("Error in D-Bus: {}", display2format!(e));
Self::new(ErrorCode::DBusError)
}
}
#[cfg(all(feature = "zbus", feature = "backtrace"))]
impl From<zbus::zvariant::Error> for Error {
fn from(e: zbus::zvariant::Error) -> Self {
Self::new_with_details(ErrorCode::DBusError, Box::new(e))
}
}
#[cfg(all(feature = "zbus", not(feature = "backtrace")))]
impl From<zbus::fdo::Error> for Error {
fn from(e: zbus::fdo::Error) -> Self {
error!("Error in D-Bus: {}", display2format!(e));
Self::new(ErrorCode::DBusError)
}
}
#[cfg(all(feature = "zbus", feature = "backtrace"))]
impl From<zbus::fdo::Error> for Error {
fn from(e: zbus::fdo::Error) -> Self {
Self::new_with_details(ErrorCode::DBusError, Box::new(e))
}
}
#[cfg(feature = "std")]
impl From<std::time::SystemTimeError> for Error {
fn from(_e: std::time::SystemTimeError) -> Self {
Error::new(ErrorCode::SysTimeFail)
}
}
impl From<TryFromSliceError> for Error {
fn from(_e: TryFromSliceError) -> Self {
Self::new(ErrorCode::Invalid)
}
}
impl From<Utf8Error> for Error {
fn from(_e: Utf8Error) -> Self {
Self::new(ErrorCode::Utf8Fail)
}
}
impl<T: num_enum::TryFromPrimitive> From<num_enum::TryFromPrimitiveError<T>> for Error {
fn from(_e: num_enum::TryFromPrimitiveError<T>) -> Self {
Self::new(ErrorCode::Invalid)
}
}
impl core::fmt::Debug for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Error::{:?}", self.code)?;
#[cfg(all(feature = "std", feature = "backtrace"))]
{
if self.backtrace.status() == std::backtrace::BacktraceStatus::Captured {
write!(f, "\n{}", self.backtrace)?;
}
}
#[cfg(all(feature = "alloc", feature = "backtrace"))]
{
if let Some(inner) = &self.inner {
write!(f, "\nCaused by: {:?}", inner)?;
}
}
Ok(())
}
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
#[cfg(all(feature = "alloc", feature = "backtrace"))]
{
let err_msg = self
.inner
.as_ref()
.map_or(Default::default(), |err| err.to_string());
if err_msg.is_empty() {
write!(f, "{:?}", self.code())
} else {
write!(f, "{:?}: {}", self.code(), err_msg)
}
}
#[cfg(not(all(feature = "alloc", feature = "backtrace")))]
{
write!(f, "{:?}", self.code())
}
}
}
#[cfg(feature = "defmt")]
impl defmt::Format for Error {
fn format(&self, f: defmt::Formatter<'_>) {
defmt::write!(f, "{:?}", self.code())
}
}
impl core::error::Error for Error {
#[cfg(all(feature = "alloc", feature = "backtrace"))]
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
self.inner
.as_ref()
.map(|e| e.as_ref() as &(dyn core::error::Error + 'static))
}
}
impl io::Error for Error {
fn kind(&self) -> io::ErrorKind {
io::ErrorKind::Other
}
}
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use core::str::from_utf8;
use super::{Error, ErrorCode};
const CODES: &[ErrorCode] = &[
ErrorCode::AlreadyExists,
ErrorCode::AttributeNotFound,
ErrorCode::BufferTooSmall,
ErrorCode::ConstraintError,
ErrorCode::Invalid,
ErrorCode::InvalidData,
ErrorCode::InvalidTransportType,
ErrorCode::NoSpace,
ErrorCode::TxTimeout,
ErrorCode::RxTimeout,
ErrorCode::StdIoError,
ErrorCode::SysTimeFail,
ErrorCode::RwLock,
ErrorCode::Utf8Fail,
ErrorCode::Failure,
ErrorCode::CdInvalidPaa,
];
#[test]
fn code_roundtrips_through_error() {
for code in CODES {
let err = Error::new(*code);
assert_eq!(err.code(), *code);
let err: Error = (*code).into();
assert_eq!(err.code(), *code);
let res: Result<(), Error> = (|| {
Err(*code)?;
Ok(())
})();
assert_eq!(res.unwrap_err().code(), *code);
}
}
#[test]
fn error_code_equality_and_hash() {
use std::collections::HashSet;
assert_eq!(ErrorCode::NoSpace, ErrorCode::NoSpace);
assert_ne!(ErrorCode::NoSpace, ErrorCode::NoSpaceExchanges);
let set: HashSet<ErrorCode> = CODES.iter().copied().collect();
assert_eq!(set.len(), CODES.len());
let a = ErrorCode::Busy;
let b = a;
assert_eq!(a, b);
}
#[test]
fn display_and_debug_do_not_panic() {
for code in CODES {
let err = Error::new(*code);
let display = format!("{err}");
let debug = format!("{err:?}");
let code_debug = format!("{code:?}");
assert!(
display.starts_with(&code_debug),
"{display} vs {code_debug}"
);
assert!(
debug.starts_with(&format!("Error::{code_debug}")),
"{debug}"
);
}
}
#[test]
fn is_peer_unresponsive_only_for_timeouts() {
assert!(Error::new(ErrorCode::TxTimeout).is_peer_unresponsive());
assert!(Error::new(ErrorCode::RxTimeout).is_peer_unresponsive());
for code in CODES {
if !matches!(code, ErrorCode::TxTimeout | ErrorCode::RxTimeout) {
assert!(!Error::new(*code).is_peer_unresponsive(), "{code:?}");
}
}
}
#[test]
fn core_conversions() {
let slice_err = <[u8; 4]>::try_from(&[1u8, 2, 3][..]).unwrap_err();
assert_eq!(Error::from(slice_err).code(), ErrorCode::Invalid);
let invalid: Vec<u8> = (0..2).map(|i| 0xff - i as u8).collect();
let utf8_err = from_utf8(&invalid).unwrap_err();
assert_eq!(Error::from(utf8_err).code(), ErrorCode::Utf8Fail);
#[derive(Debug, Copy, Clone, num_enum::TryFromPrimitive)]
#[repr(u8)]
enum Small {
_One = 1,
}
let prim_err = Small::try_from(9u8).unwrap_err();
assert_eq!(Error::from(prim_err).code(), ErrorCode::Invalid);
}
#[test]
fn error_is_a_core_error() {
let err = Error::new(ErrorCode::Busy);
let dyn_err: &dyn core::error::Error = &err;
assert!(dyn_err.source().is_none());
let boxed: Box<dyn core::error::Error + Send + Sync> = Box::new(err);
assert!(boxed.to_string().contains("Busy"));
}
#[test]
fn embedded_io_error_kind_is_other() {
use embedded_io_async::{Error as _, ErrorKind};
assert_eq!(Error::new(ErrorCode::NoSpace).kind(), ErrorKind::Other);
}
#[cfg(feature = "std")]
#[test]
fn std_conversions() {
let io = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
let err = Error::from(io);
assert_eq!(err.code(), ErrorCode::StdIoError);
let lock = std::sync::Mutex::new(());
let poisoned = std::sync::PoisonError::new(lock.lock().unwrap());
assert_eq!(Error::from(poisoned).code(), ErrorCode::RwLock);
let time_err = std::time::UNIX_EPOCH
.duration_since(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1))
.unwrap_err();
assert_eq!(Error::from(time_err).code(), ErrorCode::SysTimeFail);
}
#[cfg(all(feature = "alloc", feature = "backtrace"))]
#[test]
fn details_are_kept_and_displayed() {
let err = Error::new(ErrorCode::Busy);
assert!(err.details().is_none());
assert_eq!(format!("{err}"), "Busy");
let inner = std::io::Error::other("disk on fire");
let err = Error::new_with_details(ErrorCode::StdIoError, Box::new(inner));
assert_eq!(err.code(), ErrorCode::StdIoError);
assert!(err.details().unwrap().to_string().contains("disk on fire"));
assert_eq!(format!("{err}"), "StdIoError: disk on fire");
let dyn_err: &dyn core::error::Error = &err;
assert!(dyn_err
.source()
.unwrap()
.to_string()
.contains("disk on fire"));
#[cfg(feature = "std")]
{
let io = std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
let err = Error::from(io);
assert!(err.details().unwrap().to_string().contains("gone"));
}
}
#[cfg(all(feature = "std", feature = "backtrace"))]
#[test]
fn backtrace_capture_does_not_panic() {
let err = Error::new(ErrorCode::Failure);
let _ = err.backtrace().status();
let _ = format!("{}", err.backtrace());
let debug = format!("{err:?}");
assert!(debug.starts_with("Error::Failure"));
if err.backtrace().status() != std::backtrace::BacktraceStatus::Captured {
assert_eq!(debug, "Error::Failure");
}
}
#[cfg(all(feature = "alloc", feature = "backtrace"))]
#[test]
fn converted_error_is_kept_as_source() {
use super::{BufferError, BufferErrorCode};
let err = Error::from(BufferError::new_with_details(
BufferErrorCode::UnexpectedEof,
Box::new(std::io::Error::other("short read")),
));
assert_eq!(err.code(), ErrorCode::TruncatedPacket);
let source = core::error::Error::source(&err).unwrap();
let source = source.downcast_ref::<BufferError>().unwrap();
assert_eq!(source.code(), BufferErrorCode::UnexpectedEof);
assert_eq!(
format!("{err}"),
"TruncatedPacket: UnexpectedEof: short read"
);
let debug = format!("{err:?}");
assert!(debug.starts_with("Error::TruncatedPacket"));
assert!(debug.contains("\nCaused by: Error::UnexpectedEof"));
assert!(debug.contains("short read"));
#[cfg(feature = "std")]
{
let source = BufferError::new(BufferErrorCode::UnexpectedEof);
let captured = source.backtrace().status() == std::backtrace::BacktraceStatus::Captured;
assert_eq!(Error::from(source).details().is_some(), captured);
}
}
#[cfg(all(feature = "alloc", feature = "backtrace"))]
#[test]
fn details_can_be_downcast() {
use super::{BufferError, BufferErrorCode};
let err = Error::from(BufferError::new_with_details(
BufferErrorCode::UnexpectedEof,
Box::new(std::io::Error::other("short read")),
));
let source = err.details().unwrap().downcast_ref::<BufferError>();
let source = source.unwrap();
assert_eq!(source.code(), BufferErrorCode::UnexpectedEof);
let io = source.details().unwrap().downcast_ref::<std::io::Error>();
assert_eq!(io.unwrap().to_string(), "short read");
}
}