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&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 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 = "2" 17``` 18 19*Compiler support: requires rustc 1.61+* 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 < {max})", max = 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 that contains a `#[from]` 92 attribute. 93 94 The variant using `#[from]` must not contain any other fields beyond the 95 source error (and possibly a backtrace — see below). Usually `#[from]` 96 fields are unnamed, but `#[from]` is allowed on a named field too. 97 98 ```rust 99 #[derive(Error, Debug)] 100 pub enum MyError { 101 Io(#[from] io::Error), 102 Glob(#[from] globset::Error), 103 } 104 ``` 105 106- The Error trait's `source()` method is implemented to return whichever field 107 has a `#[source]` attribute or is named `source`, if any. This is for 108 identifying the underlying lower level error that caused your error. 109 110 The `#[from]` attribute always implies that the same field is `#[source]`, so 111 you don't ever need to specify both attributes. 112 113 Any error type that implements `std::error::Error` or dereferences to `dyn 114 std::error::Error` will work as a source. 115 116 ```rust 117 #[derive(Error, Debug)] 118 pub struct MyError { 119 msg: String, 120 #[source] // optional if field name is `source` 121 source: anyhow::Error, 122 } 123 ``` 124 125- The Error trait's `provide()` method is implemented to provide whichever field 126 has a type named `Backtrace`, if any, as a `std::backtrace::Backtrace`. Using 127 `Backtrace` in errors requires a nightly compiler with Rust version 1.73 or 128 newer. 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. The `#[backtrace]` attribute requires a nightly 144 compiler with Rust version 1.73 or newer. 145 146 147 ```rust 148 #[derive(Error, Debug)] 149 pub enum MyError { 150 Io { 151 #[backtrace] 152 source: io::Error, 153 }, 154 } 155 ``` 156 157- For variants that use `#[from]` and also contain a `Backtrace` field, a 158 backtrace is captured from within the `From` impl. 159 160 ```rust 161 #[derive(Error, Debug)] 162 pub enum MyError { 163 Io { 164 #[from] 165 source: io::Error, 166 backtrace: Backtrace, 167 }, 168 } 169 ``` 170 171- Errors may use `error(transparent)` to forward the source and Display methods 172 straight through to an underlying error without adding an additional message. 173 This would be appropriate for enums that need an "anything else" variant. 174 175 ```rust 176 #[derive(Error, Debug)] 177 pub enum MyError { 178 ... 179 180 #[error(transparent)] 181 Other(#[from] anyhow::Error), // source and Display delegate to anyhow::Error 182 } 183 ``` 184 185 Another use case is hiding implementation details of an error representation 186 behind an opaque error type, so that the representation is able to evolve 187 without breaking the crate's public API. 188 189 ```rust 190 // PublicError is public, but opaque and easy to keep compatible. 191 #[derive(Error, Debug)] 192 #[error(transparent)] 193 pub struct PublicError(#[from] ErrorRepr); 194 195 impl PublicError { 196 // Accessors for anything we do want to expose publicly. 197 } 198 199 // Private and free to change across minor version of the crate. 200 #[derive(Error, Debug)] 201 enum ErrorRepr { 202 ... 203 } 204 ``` 205 206- See also the [`anyhow`] library for a convenient single error type to use in 207 application code. 208 209 [`anyhow`]: https://github.com/dtolnay/anyhow 210 211<br> 212 213## Comparison to anyhow 214 215Use thiserror if you care about designing your own dedicated error type(s) so 216that the caller receives exactly the information that you choose in the event of 217failure. This most often applies to library-like code. Use [Anyhow] if you don't 218care what error type your functions return, you just want it to be easy. This is 219common in application-like code. 220 221[Anyhow]: https://github.com/dtolnay/anyhow 222 223<br> 224 225#### License 226 227<sup> 228Licensed under either of <a href="LICENSE-APACHE">Apache License, Version 2292.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option. 230</sup> 231 232<br> 233 234<sub> 235Unless you explicitly state otherwise, any contribution intentionally submitted 236for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 237be dual licensed as above, without any additional terms or conditions. 238</sub> 239