Skip to content

anyhow and context

Level: 201 · working knowledge

One line: anyhow gives an application one error type that anything converts into, and .context("reading ballots.txt") is what turns "No such file or directory" into a sentence naming the file.

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

  • anyhow::Result<T> is Result<T, anyhow::Error> — an alias, expandable like any other
  • Why io::Error does not contain the path it failed on, which is the gap .context() fills
  • .context(…) against .with_context(|| …): the second builds the string only on failure, which matters in a loop
  • What a chained error prints: the outermost message, then each cause
  • bail! and ensure! for the failure you raise yourself
  • The cost, stated honestly: an anyhow::Error is type-erased, so recovering a specific cause means downcast_ref

The trap it exists for

Context is added where the error is created — the deepest, least informed frame — or not at all. The useful message is usually assembled on the way out: "loading the config""reading ballots.txt""No such file or directory", each layer adding what only it knew.

See also

Po polsku

Sedno tej strony to jedno spostrzeżenie: io::Error mówi, co się stało, ale nigdy nie mówi, z czym — nie nosi w sobie ścieżki, na której poległ, więc komunikat „No such file or directory” jest prawdziwy i zupełnie bezużyteczny. Kontekst dokłada się warstwami w drodze na zewnątrz, a nie w miejscu powstania błędu, bo najgłębsza ramka wie najmniej: „wczytywanie konfiguracji” → „odczyt ballots.txt” → „No such file or directory”, gdzie każda warstwa dopisuje to, co tylko ona wiedziała. Wariant .with_context(|| …) dostaje domknięcie (closure) i skleja napis dopiero wtedy, gdy błąd faktycznie wystąpi — w pętli to różnica między jedną sklejką łańcucha a milionem. Cena, uczciwie: anyhow::Error ma wymazany typ (type-erased), więc odzyskanie konkretnej przyczyny wymaga downcast_ref — i właśnie dlatego jest to narzędzie aplikacji, a nie biblioteki.

Szukaj po polsku: kontekst błędu · łańcuch przyczyn błędu · rust anyhow context · rust io error does not include path · rust anyhow downcast_ref