Debian Codegraph @

debian/rust-vendor/thiserror/README.md

raw
1 derive(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&logo=docs.rs" height="20">](https://docs.rs/thiserror)
7 [<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/dtolnay/thiserror/ci.yml?branch=master&style=for-the-badge" height="20">](https://github.com/dtolnay/thiserror/actions?query=branch%3Amaster)
8
9 This 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]
16 thiserror = "2"
17 ```
18
19 <br>
20
21 ## Example
22
23 ```rust
24 use thiserror::Error;
25
26 #[derive(Error, Debug)]
27 pub enum DataStoreError {
28 #[error("data store disconnected")]
29 Disconnect(#[from] io::Error),
30 #[error("the data for key `{0}` is not available")]
31 Redaction(String),
32 #[error("invalid header (expected {expected:?}, found {found:?})")]
33 InvalidHeader {
34 expected: String,
35 found: String,
36 },
37 #[error("unknown data store error")]
38 Unknown,
39 }
40 ```
41
42 <br>
43
44 ## Details
45
46 - Thiserror deliberately does not appear in your public API. You get the same
47 thing as if you had written an implementation of `std::error::Error` by hand,
48 and switching from handwritten impls to thiserror or vice versa is not a
49 breaking change.
50
51 - Errors may be enums, structs with named fields, tuple structs, or unit
52 structs.
53
54 - A `Display` impl is generated for your error if you provide `#[error("...")]`
55 messages on the struct or each variant of your enum, as shown above in the
56 example.
57
58 The messages support a shorthand for interpolating fields from the error.
59
60 - `#[error("{var}")]`&ensp;⟶&ensp;`write!("{}", self.var)`
61 - `#[error("{0}")]`&ensp;⟶&ensp;`write!("{}", self.0)`
62 - `#[error("{var:?}")]`&ensp;⟶&ensp;`write!("{:?}", self.var)`
63 - `#[error("{0:?}")]`&ensp;⟶&ensp;`write!("{:?}", self.0)`
64
65 These shorthands can be used together with any additional format args, which
66 may be arbitrary expressions. For example:
67
68 ```rust
69 #[derive(Error, Debug)]
70 pub enum Error {
71 #[error("invalid rdo_lookahead_frames {0} (expected < {max})", max = i32::MAX)]
72 InvalidLookahead(u32),
73 }
74 ```
75
76 If one of the additional expression arguments needs to refer to a field of the
77 struct or enum, then refer to named fields as `.var` and tuple fields as `.0`.
78
79 ```rust
80 #[derive(Error, Debug)]
81 pub enum Error {
82 #[error("first letter must be lowercase but was {:?}", first_char(.0))]
83 WrongCase(String),
84 #[error("invalid index {idx}, expected at least {} and at most {}", .limits.lo, .limits.hi)]
85 OutOfBounds { idx: usize, limits: Limits },
86 }
87 ```
88
89 - A `From` impl is generated for each variant that contains a `#[from]`
90 attribute.
91
92 The variant using `#[from]` must not contain any other fields beyond the
93 source error (and possibly a backtrace &mdash; see below). Usually `#[from]`
94 fields are unnamed, but `#[from]` is allowed on a named field too.
95
96 ```rust
97 #[derive(Error, Debug)]
98 pub enum MyError {
99 Io(#[from] io::Error),
100 Glob(#[from] globset::Error),
101 }
102 ```
103
104 - The Error trait's `source()` method is implemented to return whichever field
105 has a `#[source]` attribute or is named `source`, if any. This is for
106 identifying the underlying lower level error that caused your error.
107
108 The `#[from]` attribute always implies that the same field is `#[source]`, so
109 you don't ever need to specify both attributes.
110
111 Any error type that implements `std::error::Error` or dereferences to `dyn
112 std::error::Error` will work as a source.
113
114 ```rust
115 #[derive(Error, Debug)]
116 pub struct MyError {
117 msg: String,
118 #[source] // optional if field name is `source`
119 source: anyhow::Error,
120 }
121 ```
122
123 - The Error trait's `provide()` method is implemented to provide whichever field
124 has a type named `Backtrace`, if any, as a `std::backtrace::Backtrace`. Using
125 `Backtrace` in errors requires a nightly compiler with Rust version 1.73 or
126 newer.
127
128 ```rust
129 use std::backtrace::Backtrace;
130
131 #[derive(Error, Debug)]
132 pub struct MyError {
133 msg: String,
134 backtrace: Backtrace, // automatically detected
135 }
136 ```
137
138 - If a field is both a source (named `source`, or has `#[source]` or `#[from]`
139 attribute) *and* is marked `#[backtrace]`, then the Error trait's `provide()`
140 method is forwarded to the source's `provide` so that both layers of the error
141 share the same backtrace. The `#[backtrace]` attribute requires a nightly
142 compiler with Rust version 1.73 or newer.
143
144
145 ```rust
146 #[derive(Error, Debug)]
147 pub enum MyError {
148 Io {
149 #[backtrace]
150 source: io::Error,
151 },
152 }
153 ```
154
155 - For variants that use `#[from]` and also contain a `Backtrace` field, a
156 backtrace is captured from within the `From` impl.
157
158 ```rust
159 #[derive(Error, Debug)]
160 pub enum MyError {
161 Io {
162 #[from]
163 source: io::Error,
164 backtrace: Backtrace,
165 },
166 }
167 ```
168
169 - Errors may use `error(transparent)` to forward the source and Display methods
170 straight through to an underlying error without adding an additional message.
171 This would be appropriate for enums that need an "anything else" variant.
172
173 ```rust
174 #[derive(Error, Debug)]
175 pub enum MyError {
176 ...
177
178 #[error(transparent)]
179 Other(#[from] anyhow::Error), // source and Display delegate to anyhow::Error
180 }
181 ```
182
183 Another use case is hiding implementation details of an error representation
184 behind an opaque error type, so that the representation is able to evolve
185 without breaking the crate's public API.
186
187 ```rust
188 // PublicError is public, but opaque and easy to keep compatible.
189 #[derive(Error, Debug)]
190 #[error(transparent)]
191 pub struct PublicError(#[from] ErrorRepr);
192
193 impl PublicError {
194 // Accessors for anything we do want to expose publicly.
195 }
196
197 // Private and free to change across minor version of the crate.
198 #[derive(Error, Debug)]
199 enum ErrorRepr {
200 ...
201 }
202 ```
203
204 - See also the [`anyhow`] library for a convenient single error type to use in
205 application code.
206
207 [`anyhow`]: https://github.com/dtolnay/anyhow
208
209 <br>
210
211 ## Comparison to anyhow
212
213 Use thiserror if you care about designing your own dedicated error type(s) so
214 that the caller receives exactly the information that you choose in the event of
215 failure. This most often applies to library-like code. Use [Anyhow] if you don't
216 care what error type your functions return, you just want it to be easy. This is
217 common in application-like code.
218
219 [Anyhow]: https://github.com/dtolnay/anyhow
220
221 <br>
222
223 #### License
224
225 <sup>
226 Licensed under either of <a href="LICENSE-APACHE">Apache License, Version
227 2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option.
228 </sup>
229
230 <br>
231
232 <sub>
233 Unless you explicitly state otherwise, any contribution intentionally submitted
234 for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
235 be dual licensed as above, without any additional terms or conditions.
236 </sub>