From ef45b181b88ab9617f26083441aaf2c448ed0761 Mon Sep 17 00:00:00 2001 From: Dominik Nakamura Date: Tue, 19 Jul 2022 15:40:39 +0900 Subject: [PATCH] Add example for expressions in `error` attribute --- README.md | 14 ++++++++++++++ src/lib.rs | 16 ++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/README.md b/README.md index 387a56e..86059ed 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,20 @@ pub enum DataStoreError { } ``` + The attribute accepts complex expressions as well. For example, if you'd like + to transform an `Option` into something else in the error messsage, you + can do so. + + ```rust + #[derive(Error, Debug)] + pub enum Error { + #[error("lost connection to the server: {}", match .0 { + Some(reason) => &reason, + None => "unknown reason", + })] + ConnectionLost(Option), + } + - A `From` impl is generated for each variant containing a `#[from]` attribute. Note that the variant must not contain any other fields beyond the source diff --git a/src/lib.rs b/src/lib.rs index 42006e3..8df3125 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -98,6 +98,22 @@ //! } //! ``` //! +//! The attribute accepts complex expressions as well. For example, if you'd like +//! to transform an `Option` into something else in the error messsage, you +//! can do so. +//! +//! ```rust +//! # use thiserror::Error; +//! +//! #[derive(Error, Debug)] +//! pub enum Error { +//! #[error("lost connection to the server: {}", match .0 { +//! Some(reason) => &reason, +//! None => "unknown reason", +//! })] +//! ConnectionLost(Option), +//! } +//! //! - A `From` impl is generated for each variant containing a `#[from]` //! attribute. //!