macron-impl-error

Crates.iomacron-impl-error
lib.rsmacron-impl-error
version0.1.1
created_at2025-04-06 14:58:46.390187+00
updated_at2025-05-25 04:16:49.790518+00
descriptionThe implementation of trait Error
homepage
repositoryhttps://github.com/fuderis/rs-macron/tree/main/macron-impl-error
max_upload_size
id1622976
size13,614
Bulat Sh. (fuderis)

documentation

README

githubcrates-iodocs-rs

Impl Error Macro

Introduction:

The implementation of trait Error.

P.s.: More useful macros you can find here.

Examples:

#[derive(Debug, Error)]
struct Error {
    source: Option<Box<dyn std::error::Error>>
}

impl ::std::fmt::Display for Error {
    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        write!(f, "it's my custom error")
    }
}

let err = Error { source: None };

assert_eq!(format!("{err}"), "it's my custom error");
#[derive(Debug, Error)]
enum Error {
    WithAnySource { source: Option<Box<dyn std::error::Error>>, msg: String },

    WithCertainSource(#[source] SourceError),

    WithoutSource
}

impl ::std::fmt::Display for Error {
    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        match &self {
            Self::WithAnySource { source, msg } => write!(f, "the error with a message: '{msg}' and a source: '{src}'", src = if let Some(src) = source.as_deref() { src.to_string() }else { "no source".to_owned() }),
            Self::WithCertainSource(src) => write!(f, "the error with the source: '{src}'"),
            Self::WithoutSource => write!(f, "the error without a source"),
        }
    }
}

#[derive(Debug, Error)]
enum SourceError {
    Error
}

impl ::std::fmt::Display for SourceError {
    fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
        match &self {
            Self::Error => write!(f, "the source of error"),
        }
    }
}

let err = Error::WithAnySource { source: Some(Box::new(SourceError::Error)), msg: "the message of error".to_owned() };
let err2 = Error::WithCertainSource( SourceError::Error );
let err3 = Error::WithoutSource;

assert_eq!(format!("{err}"), "the error with a message: 'the message of error' and a source: 'the source of error'");
assert_eq!(format!("{err2}"), "the error with the source: 'the source of error'");
assert_eq!(format!("{err3}"), "the error without a source");

Licensing:

Distributed under the MIT license.

Feedback:

You can contact me via GitHub or send a message to my Telegram @fuderis.

This library is constantly evolving, and I welcome your suggestions and feedback.

Commit count: 15

cargo fmt