• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..20-Jan-2022-

src/H20-Jan-2022-26159

tests/H20-Jan-2022-1,078867

.cargo-checksum.jsonH A D03-May-202289 11

Cargo.tomlH A D20-Jan-20221.1 KiB4035

LICENSE-APACHEH A D20-Jan-202210.6 KiB202169

LICENSE-MITH A D20-Jan-20221,023 2421

README.mdH A D20-Jan-20226.8 KiB187142

README.md

1derive(Error)
2=============
3
4[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/thiserror-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/thiserror)
5[<img alt="crates.io" src="https://img.shields.io/crates/v/thiserror.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/thiserror)
6[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-thiserror-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/thiserror)
7[<img alt="build status" src="https://img.shields.io/github/workflow/status/dtolnay/thiserror/CI/master?style=for-the-badge" height="20">](https://github.com/dtolnay/thiserror/actions?query=branch%3Amaster)
8
9This library provides a convenient derive macro for the standard library's
10[`std::error::Error`] trait.
11
12[`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html
13
14```toml
15[dependencies]
16thiserror = "1.0"
17```
18
19*Compiler support: requires rustc 1.31+*
20
21<br>
22
23## Example
24
25```rust
26use thiserror::Error;
27
28#[derive(Error, Debug)]
29pub enum DataStoreError {
30    #[error("data store disconnected")]
31    Disconnect(#[from] io::Error),
32    #[error("the data for key `{0}` is not available")]
33    Redaction(String),
34    #[error("invalid header (expected {expected:?}, found {found:?})")]
35    InvalidHeader {
36        expected: String,
37        found: String,
38    },
39    #[error("unknown data store error")]
40    Unknown,
41}
42```
43
44<br>
45
46## Details
47
48- Thiserror deliberately does not appear in your public API. You get the same
49  thing as if you had written an implementation of `std::error::Error` by hand,
50  and switching from handwritten impls to thiserror or vice versa is not a
51  breaking change.
52
53- Errors may be enums, structs with named fields, tuple structs, or unit
54  structs.
55
56- A `Display` impl is generated for your error if you provide `#[error("...")]`
57  messages on the struct or each variant of your enum, as shown above in the
58  example.
59
60  The messages support a shorthand for interpolating fields from the error.
61
62    - `#[error("{var}")]`&ensp;⟶&ensp;`write!("{}", self.var)`
63    - `#[error("{0}")]`&ensp;⟶&ensp;`write!("{}", self.0)`
64    - `#[error("{var:?}")]`&ensp;⟶&ensp;`write!("{:?}", self.var)`
65    - `#[error("{0:?}")]`&ensp;⟶&ensp;`write!("{:?}", self.0)`
66
67  These shorthands can be used together with any additional format args, which
68  may be arbitrary expressions. For example:
69
70  ```rust
71  #[derive(Error, Debug)]
72  pub enum Error {
73      #[error("invalid rdo_lookahead_frames {0} (expected < {})", i32::max_value())]
74      InvalidLookahead(u32),
75  }
76  ```
77
78  If one of the additional expression arguments needs to refer to a field of the
79  struct or enum, then refer to named fields as `.var` and tuple fields as `.0`.
80
81  ```rust
82  #[derive(Error, Debug)]
83  pub enum Error {
84      #[error("first letter must be lowercase but was {:?}", first_char(.0))]
85      WrongCase(String),
86      #[error("invalid index {idx}, expected at least {} and at most {}", .limits.lo, .limits.hi)]
87      OutOfBounds { idx: usize, limits: Limits },
88  }
89  ```
90
91- A `From` impl is generated for each variant containing a `#[from]` attribute.
92
93  Note that the variant must not contain any other fields beyond the source
94  error and possibly a backtrace. A backtrace is captured from within the `From`
95  impl if there is a field for it.
96
97  ```rust
98  #[derive(Error, Debug)]
99  pub enum MyError {
100      Io {
101          #[from]
102          source: io::Error,
103          backtrace: Backtrace,
104      },
105  }
106  ```
107
108- The Error trait's `source()` method is implemented to return whichever field
109  has a `#[source]` attribute or is named `source`, if any. This is for
110  identifying the underlying lower level error that caused your error.
111
112  The `#[from]` attribute always implies that the same field is `#[source]`, so
113  you don't ever need to specify both attributes.
114
115  Any error type that implements `std::error::Error` or dereferences to `dyn
116  std::error::Error` will work as a source.
117
118  ```rust
119  #[derive(Error, Debug)]
120  pub struct MyError {
121      msg: String,
122      #[source]  // optional if field name is `source`
123      source: anyhow::Error,
124  }
125  ```
126
127- The Error trait's `backtrace()` method is implemented to return whichever
128  field has a type named `Backtrace`, if any.
129
130  ```rust
131  use std::backtrace::Backtrace;
132
133  #[derive(Error, Debug)]
134  pub struct MyError {
135      msg: String,
136      backtrace: Backtrace,  // automatically detected
137  }
138  ```
139
140- Errors may use `error(transparent)` to forward the source and Display methods
141  straight through to an underlying error without adding an additional message.
142  This would be appropriate for enums that need an "anything else" variant.
143
144  ```rust
145  #[derive(Error, Debug)]
146  pub enum MyError {
147      ...
148
149      #[error(transparent)]
150      Other(#[from] anyhow::Error),  // source and Display delegate to anyhow::Error
151  }
152  ```
153
154- See also the [`anyhow`] library for a convenient single error type to use in
155  application code.
156
157  [`anyhow`]: https://github.com/dtolnay/anyhow
158
159<br>
160
161## Comparison to anyhow
162
163Use thiserror if you care about designing your own dedicated error type(s) so
164that the caller receives exactly the information that you choose in the event of
165failure. This most often applies to library-like code. Use [Anyhow] if you don't
166care what error type your functions return, you just want it to be easy. This is
167common in application-like code.
168
169[Anyhow]: https://github.com/dtolnay/anyhow
170
171<br>
172
173#### License
174
175<sup>
176Licensed under either of <a href="LICENSE-APACHE">Apache License, Version
1772.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option.
178</sup>
179
180<br>
181
182<sub>
183Unless you explicitly state otherwise, any contribution intentionally submitted
184for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
185be dual licensed as above, without any additional terms or conditions.
186</sub>
187