rust-error-handling
Skill1 starsChanged 2 months agoMITView on GitHub
Pick and use the right Rust error strategy - thiserror for library error enums with #[source] chains, anyhow for application/binary error context, eyre for reportable application errors, converting between them, and the modern gotchas around `?`, Box<dyn Error>, and trait objects. Use when designing a crate's error API, when a user asks "thiserror vs anyhow", "add context to an error", "define a custom error", or when fixing "the ? operator", "source()", "downcast". Triggers on "anyhow", "thiserror", "eyre", "Box<dyn Error>", "error chain", "context()", "From impl for errors", "Result<T, E>".
6 other projects use a version of this.
Adopted by
Most recently taken up by
- saizul/rust-dev-skillstheir own version, first seen Nov 29, 2026
- po4yka/rust-skillstheir own version, first seen Nov 15, 2026
- adxptived/Rust-Skillstheir own version, first seen Oct 17, 2026
- opensite-ai/opensite-skillstheir own version, first seen Oct 13, 2026
- botirkhaltaev/botir-skillstheir own version, first seen Jul 24, 2026
- codecharmhq/claude-code-skillstheir own version, first seen May 17, 2026
Used with
Projects with it also use rust-performance.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
huialiSkillrust-performance
Performance optimization expert covering profiling, benchmarking, memory allocation, SIMD, cache optimization, false sharing, lock contention, and NUMA-aware programming.
Also in 3 projects that use this
Other versions6 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 6
- opensite-ai/opensite-skills★ 15same name
- po4yka/rust-skills★ 7same name
- botirkhaltaev/botir-skills★ 4same name
- adxptived/Rust-Skills★ 1same name
- codecharmhq/claude-code-skills★ 1same name
- saizul/rust-dev-skills★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository126 other files it gives its agents.
- eu-data-backend-job-hunterSkill
- job-application-matcherSkill
- llm-agents-and-tool-useSkill
- llm-application-architectureSkill
- llm-cost-and-latency-optimizationSkill
- llm-evaluationSkill
- llm-fine-tuning-and-adaptersSkill
- llm-privacy-and-safetySkill
- llm-prompt-engineeringSkill
- llm-rag-systemsSkill
- structured-output-and-jsonSkill
- graphql-api-designSkill
- pagination-and-filteringSkill
- rest-api-designSkill
- webhooks-and-integrationsSkill
- caching-architecture-multi-layerSkill
- resilience-patternsSkill
- service-boundaries-and-monolithsSkill
- system-design-interviewSkill
- go-concurrencySkill
- go-error-handlingSkill
- java-spring-patternsSkill
- nodejs-server-performanceSkill
- python-async-patternsSkill
- python-data-modelingSkill
- python-packaging-and-toolingSkill
- python-performanceSkill
- rest-api-implementationSkill
- rust-ownership-patternsSkill
- typescript-type-safetySkill
- ci-caching-and-speedupSkill
- ci-pipeline-designSkill
- deployment-strategiesSkill
- github-actions-hardeningSkill
- release-versioning-and-changelogsSkill
- reproducible-buildsSkill
- aws-iam-and-securitySkill
- aws-serverless-architectureSkill
- azure-fundamentalsSkill
- cloud-cost-optimizationSkill
- cloud-networking-and-vpcSkill
- gcp-cloud-architectureSkill
- code-review-skillsSkill
- design-review-and-refactoring-architectureSkill
- refactoring-techniqueSkill
- understanding-unknown-codebaseSkill
- buildkit-and-cacheSkill
- container-image-debuggingSkill
- container-runtime-securitySkill
- docker-compose-workflowsSkill
- dockerfile-authoringSkill
- docker-image-optimizationSkill
- database-connection-managementSkill
- database-transactionsSkill
- distributed-databasesSkill
- nosql-data-modelingSkill
- postgres-query-tuningSkill
- redis-and-cachingSkill
- schema-migrationsSkill
- data-modeling-for-analyticsSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
3 rules. 0 are common, 0 are distinctive, and 3 are very specific to this project.
0
Common
Most of the 4 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 123
.context(msg)/.with_context(|| ...): add a layer above the error without losing it. - Very specific: line 184
A trait method's error type: must be fixed in the trait.
- Very specific: line 204
Binary: add .context(...) at each step that a human would want described.
“Common” is measured: kept by at least 6 in 10 of the 4 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Rust Error Handling
Rust's default is Result<T, E> with no implicit context: a ? either
returns the exact error or converts it. Libraries should let callers decide
what an error means, so a library defines a concrete error enum; binaries add
human-readable context as it propagates up. The modern split is
thiserror for libraries, anyhow (or eyre) for applications.
The decision
| The crate is… | Use | Why |
| A library others depend on | thiserror + a concrete enum Error | Callers can match on variants; the type is part of your API; no dyn dispatch, no surprise |
| A binary / service / CLI | anyhow::Result | You only need "did it fail, and what do I tell the operator"; ad-hoc context with .context() is the point |
A binary that needs a Report with spans/backtraces | eyre | Like anyhow, plus optional SpanTrace/location capture; opt-in via the track-caller feature |
Anything that must be no_std | core::error::Error + a hand-written enum | thiserror works, but std::error::Error is unstable to implement manually on stable — see Gotchas |
Rule of thumb: libraries never use anyhow/Box<dyn Error> in a public
signature. That erases the error type and forces every caller to downcast. A
library's Error enum is a public API you version; treat it as one.
thiserror: library errors
[dependencies]
thiserror = "2"use std::num::ParseIntError;
use std::io;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("could not read config from {path}")]
ReadConfig {
path: String,
#[source] // the cause; shows in the chain
source: io::Error,
},
#[error("config value {key:?} is invalid")]
InvalidValue {
key: String,
reason: &'static str, // data on the variant, no source
},
#[error("could not parse port")]
ParsePort(#[from] ParseIntError), // #[from] generates a From impl
#[error("database unavailable")] // unit variant: a category
Unavailable,
}
pub fn load(path: &str) -> Result<Config, Error> {
let text = std::fs::read_to_string(path).map_err(|source| {
Error::ReadConfig { path: path.to_string(), source }
})?;
let port: u16 = text.trim().parse()?; // ? uses the #[from] From impl
if port == 0 {
return Err(Error::InvalidValue { key: "port".into(), reason: "must be non-zero" });
}
Ok(Config { port })
}The spellings that matter:
#[error("...")]— theDisplaystring. Use{field}interpolation (thiserror 1.x/2.x both support{}in the format string for fields);.0/.1for tuple fields. Do not put the source in the message by hand —#[source]handles the chain.#[source]— marks the field as the cause.source()returns it, andanyhow/eyreprint the full chain. Use#[from]instead of#[source]when you also want a generatedFromimpl.#[from]— generatesimpl From<T> for Error. You get oneFromper variant, so two variants cannot both#[from]the same type (a coherence conflict). If you need to distinguish twoio::Errors, use#[source]and wrap manually.#[error(transparent)]— forwardsDisplay,source(), and the exit code to the wrapped error, with no added message. Use for a variant that is purely "pass the cause through" (e.g. wrapping a lower-layer error enum).- Unit variants (
Unavailable) are fine for a category with no data. Callersmatchon them.
Rule: a library error enum should let a caller exhaustively match the
interesting cases. If your enum has 20 variants and a caller must read the
Display string to decide, the design is wrong.
anyhow: application errors and context
[dependencies]
anyhow = "1"use anyhow::{Context, Result, bail, ensure, anyhow};
fn load_config(path: &str) -> Result<Config> { // note: anyhow::Result
let text = std::fs::read_to_string(path)
.with_context(|| format!("reading config {path}"))?;
let port: u16 = text.trim().parse()
.context("port is not a number")?;
ensure!(port > 0, "port must be non-zero, got {port}"); // returns Err
if port == 0 { bail!("port must be non-zero"); } // early return
Ok(Config { port })
}
fn main() -> Result<()> { // one line, the whole binary
let cfg = load_config("app.toml")?; // ? converts to anyhow::Error
run(cfg)?;
Ok(())
}.context(msg)/.with_context(|| ...)add a layer above the error without losing it..with_contexttakes a closure so the string is only built if there is an error — use it when formatting is non-trivial..context("reading config")on a static string is fine and cheaper.- The printed chain is:
(roughly — the outer message plus each source). This is what a human operator wants; a library should not produce it.Error: reading config app.toml Caused by: 0: No such file or directory (os error 2) 1: reading config app.toml bail!= earlyreturn Err(anyhow!(...)).ensure!(cond, ...)=if !cond { bail!(...) }. Both are macros overanyhow!.anyhow!creates an ad-hoc error with no type. Fine in a binary; do not leak it out of a library function.anyhow::Resultin a public library signature is a mistake. It erases the type, forces callers todowncast, and couples your library to anyhow. UseResult<T, YourError>.
eyre: like anyhow, with reports
eyre = { version = "0.6", optional = true }Drop-in for anyhow (eyre::Result, .wrap_err(...) instead of
.context(...), ? from WrapErr). Add it when you want a Report that can
carry a SpanTrace/location for error reporting. Feature flags
(auto-install, track-caller) change the behaviour; read the crate's
feature docs before enabling. For a service that reports errors to a tracker,
eyre is the better anyhow.
The ? operator and trait objects — the real gotchas
?onResult<T, E>needsE: Into<YourError>. For a thiserror#[from], thatFromimpl exists. Without it,?fails to compile — the fix is aFromimpl, not a.map_errat every site.Box<dyn std::error::Error>in a signature is legal and compiles, but it means the caller mustdowncast_ref/downcastto learn anything, and you lose the ability to match variants. Acceptable in a binary; avoid in a library signature. If you must in a library, document that callers should downcast to your concrete type, and expose the concrete type publicly so they can.Box<dyn Error + Send + Sync + 'static>is the form required when the error crosses a thread boundary (tokio::spawn, astd::threadclosure result, ananyhowin a trait object).Box<dyn Error>alone is notSend, soanyhow::Error(which isSend + Sync) usually is. The exact bound matters when a generic function needs the error to cross threads.- Downcasting:
if let Some(io) = e.downcast_ref::<std::io::Error>() { /* ... */ } if let Some(my) = e.downcast_ref::<mycrate::Error>() { /* ... */ } let concrete = e.downcast::<std::io::Error>(); // consumes, returns Result<io, Error>downcastrequires the target to implementError + 'static. impl Error for MyErroris still unstable (std::error::Errorcannot be implemented manually on stable withoutthiserror). That is exactly whythiserrorexists — it is a proc-macro that writes the impl. Do not try to hand-writeimpl std::error::Erroron stable; it will not compile.- A trait method's error type must be fixed in the trait. If a trait's
methods can fail with different concrete types per implementor, either use
anyhow::Error(and accept the coupling) or define an associated error type and aFrombound. Do not return a differentEper impl without declaring it in the trait. - Converting a library error into an anyhow error happens automatically:
anyhow::Error: From<E> where E: std::error::Error + Send + Sync + 'static. A thiserror enum satisfies this, so.context(...)works on a library error directly. If your error is notSend + Sync(e.g. it holds anRc),anyhowcannot take it — this is a real constraint, and a reason to useArcin your error types.
Sources and context chains — the model
An error has two parts: a Display message for humans and a source() chain
for machines. Build both:
- Library: define the enum with
#[source], sosource()walks the real cause. Wrap lower-layer errors; never re-format them into a string (that destroys the chain). - Binary: add
.context(...)at each step that a human would want described. The innermost error is the technical cause; each context layer says what the program was trying to do. - Do not duplicate the source in the
Displaystring ("failed to read config: No such file") and keep#[source]—anyhowprints both and you get the message twice. The#[error("could not read config from {path}")]message describes the operation; the source is the cause.
Gotchas
- Do not use
anyhowin a library's public API. It is the single most common Rust error-handling mistake and it is hard to undo once published. - Do not return
Stringas an error type in a library. You losesource(), matching, and the ability for a caller to distinguish cases. #[error(transparent)]on a variant that wraps a multi-error still forwardssource(), but it adds no context — if you want context, write the message and keep#[source].- An error enum with a
#[from]forstd::io::Errorand another for a different type that is alsoio::Errorvia a newtype works, but two#[from]variants with the same source type do not compile (conflictingFromimpls). Use#[source]+ manual wrapping in that case. unwrap()in amainis fine; in a library it is a bug. A panic in a library called from a server aborts that request or the process; returnResult.expect("...")is better thanunwrap()because the message survives, but it is still a panic. Only for genuine invariants.- Error enums are non-exhaustive in practice as you add variants. Adding
one is technically a breaking change for a downstream
matchwithout a_arm; mark the enum#[non_exhaustive]if you plan to grow it. thiserrorderive generatesDisplayandError; it does not generateFromunless you add#[from]. Forgetting#[from]is why?stops compiling and you reach for.map_err(to_string).- Panic in a
Dropimpl during unwinding causes a double panic and aborts the process.Dropmust not panic.
Quick decision checklist
- Is this a library? Concrete
enum+thiserror,Fromimpls,#[source]chain, noanyhowin signatures. - Is this a binary?
anyhow::Result/eyre::Result,.context()at each meaningful step, onemainthat reports and exits non-zero. - Does a caller need to match on this failure? It must be a typed
variant, not a string — otherwise use a typed error, not
anyhow. - Does the error cross a thread? It must be
Send + Sync + 'static; useArc, notRc, inside it. - Is
impl std::error::Errorbeing hand-written? Usethiserror— it is not implementable manually on stable.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

