API Reference

thiserror

Library for deriving structured error enums in Rust with display formats and source chaining.

Official Documentation ↗
CompatibilityThis documentation covers version v2. Check the official docs for the latest API surface.

Installation

cargocargo add thiserror

Methods

Library for deriving structured error enums in Rust with display formats and source chaining.

Overview

thiserror turns error enums into first-class library APIs. A derive plus per-variant format strings produce Display, std::error::Error, source chaining, and optional From conversions, without hand-writing impls.

Callers can match variants exhaustively, and the displayed messages stay consistent wherever the errors surface. It pairs with anyhow naturally: libraries expose thiserror types, applications wrap them with context.

Core Methods

The most frequently used entry points, with signatures and runnable examples:

  • #[derive(Error)] — Generates std::error::Error and Display for the enum from format attributes.
  • #[from] / #[source] — Bridges underlying errors: #[from] adds From conversion, #[source] links the cause chain.
  • #[error(transparent)] — Forwards Display and source straight through to a single wrapped inner error.

Usage Notes

  • Design variants around what callers must distinguish, not around internal call sites.
  • Include the identifying fields, id, endpoint, in the format so messages are actionable.
  • Reserve transparent for pure re-exports where the inner message is already complete.

Common Pitfalls

  • Variant sprawl: wrapping every underlying error erodes the value of matching; model the distinctions callers need.
  • Forgetting #[from] means every propagation needs .map_err, inflating call sites.
  • Format strings that omit fields produce identical messages for different variants.

Errors

The following points are quoted verbatim from the official documentation. 来源:https://cdn.jsdelivr.net/gh/dtolnay/thiserror@latest/README.md · 取证方式:HTTP GET 官方 README/文档页(HTML 去标签) · 抓取时间:2026-11-07T13:52:59.998Z. Any error type, throw condition or recovery step not stated there is left unspecified; this page does not infer exception classes or return values.

FAQ

Why derive instead of implementing Error manually?
Manual impls are repetitive boilerplate, display formats, source links, From conversions, that thiserror generates declaratively. The derived types remain ordinary enums, so matching on variants works exactly as before.
Can one variant have both #[from] and a custom message?
Yes: #[from] only generates the From impl and links the source; the #[error("...")] attribute still controls Display. Only transparent forwards the inner message, which is a different, deliberate choice.
Does thiserror work in no_std?
Yes, thiserror 2 supports no_std targets since it depends only on core error traits. That makes it usable in embedded and kernel-adjacent crates where anyhow would be heavier.