← All notes

thiserror derives std::error::Error with #[error], #[from], #[source] and transparent variants

Answer: Add #[derive(Error, Debug)] to an enum or struct, give each variant an #[error("...")] message, and mark wrapped errors with #[from]. thiserror is a derive macro for the standard library's std::error::Error trait and deliberately does not appear in your public API.

Example

use thiserror::Error;

#[derive(Error, Debug)]
pub enum DataStoreError {
    #[error("data store disconnected")]
    Disconnect(#[from] io::Error),
    #[error("the data for key `{0}` is not available")]
    Redaction(String),
    #[error("invalid header (expected {expected:?}, found {found:?})")]
    InvalidHeader { expected: String, found: String },
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

Attributes

Details

thiserror or anyhow

Use thiserror if you care about designing your own dedicated error types, which most often applies to library-like code. Use Anyhow in application-like code.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: docs.rs, Crate thiserror; dtolnay/thiserror (GitHub), README. MIT OR Apache-2.0 (https://raw.githubusercontent.com/dtolnay/anyhow/master/LICENSE-APACHE). Copyright David Tolnay. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: docs.rs, Crate thiserror; dtolnay/thiserror (GitHub), README. MIT OR Apache-2.0 (https://raw.githubusercontent.com/dtolnay/anyhow/master/LICENSE-APACHE). Copyright David Tolnay.

Cite this

Permanent ID: iil:note:t89m2dgq

iinventedlight. 2026. "thiserror derives std::error::Error with error, from, source and transparent attributes." iinventedlight Library, iil:note:t89m2dgq, version of 2026-11-18. https://iinventedlight.com/library/notes/rust-thiserror/. License: CC-BY-4.0.

@misc{iil_note_t89m2dgq,
  author = {{iinventedlight}},
  title = {{thiserror derives std::error::Error with error, from, source and transparent attributes}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-18},
  url = {https://iinventedlight.com/library/notes/rust-thiserror/},
  note = {Permanent ID iil:note:t89m2dgq. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/rust-thiserror.md.