thiserror vs anyhow¶
Level: 301 · deep dive
One line: A library names its errors so callers can decide; an application erases them because the only remaining decision is what to print — and the whole choice is which side of that line your code is on.
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The bullets below are the questions the finished page has to answer.
What it has to cover¶
thiserror↗ is a boilerplate remover, not a new error model: it derivesDisplay,ErrorandFromon an enum you would otherwise write by handanyhow↗ is a type-erased error for the top of a program, where the caller is a person- Why
anyhow::Resultin a public API is a dead end: the caller can print it and nothing else - Error types are semver-visible — adding a variant is a breaking change unless the enum is
#[non_exhaustive] - The common shape: a binary with a library half,
thiserrorinside,anyhowinmain - What you give up either way, so the page ends on a trade rather than a rule
The trap it exists for¶
The crates are not rivals, so "which is better" has no answer — and picking one by habit is how a library ends up returning anyhow::Error to callers who needed to distinguish file missing from file malformed. The question is never which crate; it is whether anyone downstream has a decision to make.
See also¶
anyhowand context — the application side, in detail- Not every error is an
io::Error— the problem both crates are answering OptionvsResult— Steps 8 and 9: designing theE, and deciding not to
Po polsku¶
Pytanie „który crate jest lepszy” jest tu źle postawione, bo te dwa ze sobą nie konkurują — a ich nazwy są właściwie odpowiedzią, nie znakami firmowymi: thiserror to ten konkretny błąd, anyhow to byle jakoś, bylebym mógł to wypisać. thiserror nie wprowadza żadnego nowego modelu błędów; generuje z atrybutów Display, Error i From na wyliczeniu, które i tak napisałbyś ręcznie — model zostaje ten sam, znika wyłącznie powtarzalny kod (boilerplate). anyhow stoi na przeciwnym końcu programu, tam gdzie wywołującym jest człowiek, a jedyną pozostałą decyzją jest treść komunikatu; w publicznym API biblioteki anyhow::Result to ślepa uliczka, bo odbiorca może już tylko wypisać to, co dostał. Właściwe pytanie brzmi więc: czy ktokolwiek dalej w łańcuchu ma jeszcze jakąś decyzję do podjęcia — jeśli tak, nazwij błędy (pamiętając, że typ błędu jest widoczny w semver, więc dodanie wariantu bez #[non_exhaustive] łamie zgodność); jeśli nie, wymaż je i nie udawaj, że jest inaczej.
Szukaj po polsku: obsługa błędów w bibliotece · własne typy błędów · rust thiserror vs anyhow · rust anyhow in public api · rust non_exhaustive semver