From cd9f19a4548d07ef65fb941458dd5f79cc4d7e51 Mon Sep 17 00:00:00 2001 From: Andrew Kozin Date: Mon, 31 Jul 2023 20:27:52 +0100 Subject: [PATCH] Stop requiring error kinds to impl Display 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). --- async-nats/src/error.rs | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/async-nats/src/error.rs b/async-nats/src/error.rs index 13cd633af..770743abb 100644 --- a/async-nats/src/error.rs +++ b/async-nats/src/error.rs @@ -13,11 +13,16 @@ use std::fmt::{Debug, Display}; +// A trait to mark enums that can be used as error kinds. +pub trait ErrorKind: Clone + Debug + PartialEq {} + +impl 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 where - Kind: Clone + Debug + Display + PartialEq, + Kind: ErrorKind, { pub(crate) kind: Kind, pub(crate) source: Option, @@ -25,7 +30,7 @@ where impl Error where - Kind: Clone + Debug + Display + PartialEq, + Kind: ErrorKind, { pub(crate) fn new(kind: Kind) -> Self { Self { kind, source: None } @@ -49,7 +54,7 @@ where impl Display for Error 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 { @@ -60,11 +65,16 @@ where } } -impl std::error::Error for Error where Kind: Clone + Debug + Display + PartialEq {} +impl std::error::Error for Error +where + Kind: ErrorKind, + Error: Display, +{ +} impl From for Error where - Kind: Clone + Debug + Display + PartialEq, + Kind: ErrorKind, { fn from(kind: Kind) -> Self { Self { kind, source: None } @@ -75,7 +85,7 @@ where /// by additionally specifying the kind of the target error. trait WithKind where - Kind: Clone + Debug + Display + PartialEq, + Kind: ErrorKind, Self: Into, { fn with_kind(self, kind: Kind) -> Error { @@ -88,7 +98,7 @@ where impl WithKind for E where - Kind: Clone + Debug + Display + PartialEq, + Kind: ErrorKind, E: Into, { }