| 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 = "1.0" |
| 17 |
``` |
| 18 |
|
| 19 |
*Compiler support: requires rustc 1.56+* |
| 20 |
|
| 21 |
<br> |
| 22 |
|
| 23 |
## Example |
| 24 |
|
| 25 |
```rust |
| 26 |
use thiserror::Error; |
| 27 |
|
| 28 |
#[derive(Error, Debug)] |
| 29 |
pub 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 `provide()` method is implemented to provide whichever field |
| 128 |
has a type named `Backtrace`, if any, as a `std::backtrace::Backtrace`. |
| 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 `provide()` |
| 142 |
method is forwarded to the source's `provide` so that both layers of the error |
| 143 |
share the same backtrace. |
| 144 |
|
| 145 |
```rust |
| 146 |
#[derive(Error, Debug)] |
| 147 |
pub enum MyError { |
| 148 |
Io { |
| 149 |
#[backtrace] |
| 150 |
source: io::Error, |
| 151 |
}, |
| 152 |
} |
| 153 |
``` |
| 154 |
|
| 155 |
- Errors may use `error(transparent)` to forward the source and Display methods |
| 156 |
straight through to an underlying error without adding an additional message. |
| 157 |
This would be appropriate for enums that need an "anything else" variant. |
| 158 |
|
| 159 |
```rust |
| 160 |
#[derive(Error, Debug)] |
| 161 |
pub enum MyError { |
| 162 |
... |
| 163 |
|
| 164 |
#[error(transparent)] |
| 165 |
Other(#[from] anyhow::Error), // source and Display delegate to anyhow::Error |
| 166 |
} |
| 167 |
``` |
| 168 |
|
| 169 |
Another use case is hiding implementation details of an error representation |
| 170 |
behind an opaque error type, so that the representation is able to evolve |
| 171 |
without breaking the crate's public API. |
| 172 |
|
| 173 |
```rust |
| 174 |
// PublicError is public, but opaque and easy to keep compatible. |
| 175 |
#[derive(Error, Debug)] |
| 176 |
#[error(transparent)] |
| 177 |
pub struct PublicError(#[from] ErrorRepr); |
| 178 |
|
| 179 |
impl PublicError { |
| 180 |
// Accessors for anything we do want to expose publicly. |
| 181 |
} |
| 182 |
|
| 183 |
// Private and free to change across minor version of the crate. |
| 184 |
#[derive(Error, Debug)] |
| 185 |
enum ErrorRepr { |
| 186 |
... |
| 187 |
} |
| 188 |
``` |
| 189 |
|
| 190 |
- See also the [`anyhow`] library for a convenient single error type to use in |
| 191 |
application code. |
| 192 |
|
| 193 |
[`anyhow`]: https://github.com/dtolnay/anyhow |
| 194 |
|
| 195 |
<br> |
| 196 |
|
| 197 |
## Comparison to anyhow |
| 198 |
|
| 199 |
Use thiserror if you care about designing your own dedicated error type(s) so |
| 200 |
that the caller receives exactly the information that you choose in the event of |
| 201 |
failure. This most often applies to library-like code. Use [Anyhow] if you don't |
| 202 |
care what error type your functions return, you just want it to be easy. This is |
| 203 |
common in application-like code. |
| 204 |
|
| 205 |
[Anyhow]: https://github.com/dtolnay/anyhow |
| 206 |
|
| 207 |
<br> |
| 208 |
|
| 209 |
#### License |
| 210 |
|
| 211 |
<sup> |
| 212 |
Licensed under either of <a href="LICENSE-APACHE">Apache License, Version |
| 213 |
2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option. |
| 214 |
</sup> |
| 215 |
|
| 216 |
<br> |
| 217 |
|
| 218 |
<sub> |
| 219 |
Unless you explicitly state otherwise, any contribution intentionally submitted |
| 220 |
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall |
| 221 |
be dual licensed as above, without any additional terms or conditions. |
| 222 |
</sub> |