Skip to content

Commit

Permalink
Stop requiring error kinds to impl Display
Browse files Browse the repository at this point in the history
All kinds of `error::Error` now implements the `Display` trait,
and the `Display` for the `Error` itself is inherited.

The binding between the kind and `Display` is not necessary though.

In this commit I dropped the restriction of error kinds by `Display`,
and only implemented the trait for errors with displayable kinds.
As a result, the developer got 2 options:

- either to implement the `Display` for the kind (preferred),
- or implement it for the error only (but not for the kind) (edge case).
  • Loading branch information
nepalez committed Aug 2, 2023
1 parent 6d38be9 commit cd9f19a
Showing 1 changed file with 17 additions and 7 deletions.
24 changes: 17 additions & 7 deletions async-nats/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,24 @@

use std::fmt::{Debug, Display};

// A trait to mark enums that can be used as error kinds.
pub trait ErrorKind: Clone + Debug + PartialEq {}

impl<T> ErrorKind for T where T: Clone + Debug + PartialEq {}

/// The error type for the NATS client, generic by the kind of error.
#[derive(Debug)]
pub struct Error<Kind>
where
Kind: Clone + Debug + Display + PartialEq,
Kind: ErrorKind,
{
pub(crate) kind: Kind,
pub(crate) source: Option<crate::Error>,
}

impl<Kind> Error<Kind>
where
Kind: Clone + Debug + Display + PartialEq,
Kind: ErrorKind,
{
pub(crate) fn new(kind: Kind) -> Self {
Self { kind, source: None }
Expand All @@ -49,7 +54,7 @@ where

impl<Kind> Display for Error<Kind>
where
Kind: Clone + Debug + Display + PartialEq,
Kind: ErrorKind + Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(err) = &self.source {
Expand All @@ -60,11 +65,16 @@ where
}
}

impl<Kind> std::error::Error for Error<Kind> where Kind: Clone + Debug + Display + PartialEq {}
impl<Kind> std::error::Error for Error<Kind>
where
Kind: ErrorKind,
Error<Kind>: Display,
{
}

impl<Kind> From<Kind> for Error<Kind>
where
Kind: Clone + Debug + Display + PartialEq,
Kind: ErrorKind,
{
fn from(kind: Kind) -> Self {
Self { kind, source: None }
Expand All @@ -75,7 +85,7 @@ where
/// by additionally specifying the kind of the target error.
trait WithKind<Kind>
where
Kind: Clone + Debug + Display + PartialEq,
Kind: ErrorKind,
Self: Into<crate::Error>,
{
fn with_kind(self, kind: Kind) -> Error<Kind> {
Expand All @@ -88,7 +98,7 @@ where

impl<E, Kind> WithKind<Kind> for E
where
Kind: Clone + Debug + Display + PartialEq,
Kind: ErrorKind,
E: Into<crate::Error>,
{
}
Expand Down

0 comments on commit cd9f19a

Please sign in to comment.