|
14 | 14 | //! #[derive(Error, Debug)] |
15 | 15 | //! pub enum DataStoreError { |
16 | 16 | //! #[error("data store disconnected")] |
17 | | -//! Disconnect(#[source] io::Error), |
| 17 | +//! Disconnect(#[from] io::Error), |
18 | 18 | //! #[error("the data for key `{0}` is not available")] |
19 | 19 | //! Redaction(String), |
20 | 20 | //! #[error("invalid header (expected {expected:?}, found {found:?})")] |
|
67 | 67 | //! } |
68 | 68 | //! ``` |
69 | 69 | //! |
| 70 | +//! - A `From` impl is generated for each variant containing a `#[from]` |
| 71 | +//! attribute. |
| 72 | +//! |
| 73 | +//! Note that the variant must not contain any other fields beyond the source |
| 74 | +//! error and possibly a backtrace. A backtrace is captured from within the |
| 75 | +//! `From` impl if there is a field for it. |
| 76 | +//! |
| 77 | +//! ```rust |
| 78 | +//! # const IGNORE: &str = stringify! { |
| 79 | +//! #[derive(Error, Debug)] |
| 80 | +//! pub enum MyError { |
| 81 | +//! Io { |
| 82 | +//! #[from] |
| 83 | +//! source: io::Error, |
| 84 | +//! backtrace: Backtrace, |
| 85 | +//! }, |
| 86 | +//! } |
| 87 | +//! # }; |
| 88 | +//! ``` |
| 89 | +//! |
70 | 90 | //! - The Error trait's `source()` method is implemented to return whichever |
71 | | -//! field has a `#[source]` attribute, if any. This is for identifying the |
72 | | -//! underlying lower level error that caused your error. |
| 91 | +//! field has a `#[source]` attribute or is named `source`, if any. This is |
| 92 | +//! for identifying the underlying lower level error that caused your error. |
| 93 | +//! |
| 94 | +//! The `#[from]` attribute always implies that the same field is `#[source]`, |
| 95 | +//! so you don't ever need to specify both attributes. |
73 | 96 | //! |
74 | 97 | //! Any error type that implements `std::error::Error` or dereferences to `dyn |
75 | 98 | //! std::error::Error` will work as a source. |
|
81 | 104 | //! #[derive(Error, Debug)] |
82 | 105 | //! pub struct MyError { |
83 | 106 | //! msg: String, |
84 | | -//! #[source] |
| 107 | +//! #[source] // optional if field name is `source` |
85 | 108 | //! source: anyhow::Error, |
86 | 109 | //! } |
87 | 110 | //! # |
|
0 commit comments