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}")]` ⟶ `write!("{}", self.var)`
63 - `#[error("{0}")]` ⟶ `write!("{}", self.0)`
64 - `#[error("{var:?}")]` ⟶ `write!("{:?}", self.var)`
65 - `#[error("{0:?}")]` ⟶ `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)]
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- If a field is both a source (named `source`, or has `#[source]` or `#[from]`
141 attribute) *and* is marked `#[backtrace]`, then the Error trait's
142 `backtrace()` method is forwarded to the source's backtrace.
143
144 ```rust
145 #[derive(Error, Debug)]
146 pub enum MyError {
147 Io {
148 #[backtrace]
149 source: io::Error,
150 },
151 }
152 ```
153
154- Errors may use `error(transparent)` to forward the source and Display methods
155 straight through to an underlying error without adding an additional message.
156 This would be appropriate for enums that need an "anything else" variant.
157
158 ```rust
159 #[derive(Error, Debug)]
160 pub enum MyError {
161 ...
162
163 #[error(transparent)]
164 Other(#[from] anyhow::Error), // source and Display delegate to anyhow::Error
165 }
166 ```
167
168- See also the [`anyhow`] library for a convenient single error type to use in
169 application code.
170
171 [`anyhow`]: https://github.com/dtolnay/anyhow
172
173<br>
174
175## Comparison to anyhow
176
177Use thiserror if you care about designing your own dedicated error type(s) so
178that the caller receives exactly the information that you choose in the event of
179failure. This most often applies to library-like code. Use [Anyhow] if you don't
180care what error type your functions return, you just want it to be easy. This is
181common in application-like code.
182
183[Anyhow]: https://github.com/dtolnay/anyhow
184
185<br>
186
187#### License
188
189<sup>
190Licensed under either of <a href="LICENSE-APACHE">Apache License, Version
1912.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option.
192</sup>
193
194<br>
195
196<sub>
197Unless you explicitly state otherwise, any contribution intentionally submitted
198for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
199be dual licensed as above, without any additional terms or conditions.
200</sub>
201