skip to content

Errors and Panics

Rust has no exceptions: recoverable failures are Result values and bugs are panics. Interviewers test the ? operator, custom error types, library vs application errors and panics.

on this pageshow

explore

questions

page 1 of 2

In a Rust tool using anyhow, how do you make an io::Error from fs::read_to_string say which manifest file failed?

level: juniorimportance: must knowfreq 60%

answer

  1. an extension trait to import
  2. a method on the Result
  3. a closure for formatted text
  4. the io::Error stays underneath

basics

~10 s

Import anyhow::Context and call .with_context(|| format!("failed to load manifest {}", path.display())) on the Result. The Err becomes an anyhow::Error whose message names the file, with the original io::Error kept as its source.

solid answer

~40 s

A `std::io::Error` from `fs::read_to_string` says `No such file or directory (os error 2)` but does not include the path. With anyhow, bring the extension trait into scope with `use anyhow::Context;` and write `fs::read_to_string(path).with_context(|| format!("failed to load manifest {}", path.display()))?`. That turns `Result<String, io::Error>` into `anyhow::Result<String>`: the new message becomes the error's `Display`, and the `io::Error` is kept underneath as its source, so `{:#}` prints both and `downcast_ref::<io::Error>()` still finds it. Use `.context("fixed text")` when the message is a constant; `with_context` takes a closure, so the `format!` runs only on the error path. Both methods also work on `Option`, turning `None` into an error.

code

rust · 17 lines
rust
use anyhow::{Context, Result};
use std::fs;
use std::path::Path;

fn load_manifest(path: &Path) -> Result<String> {
    let text = fs::read_to_string(path)
        .with_context(|| format!("failed to load manifest {}", path.display()))?;
    Ok(text)
}

fn main() {
    let err = load_manifest(Path::new("deploy/prod.toml")).unwrap_err();
    println!("{err}");
    println!("{err:#}");
    let io = err.downcast_ref::<std::io::Error>().unwrap();
    println!("io kind: {:?}", io.kind());
}

go deeper

for a junior

Recall the import, use anyhow::Context, and the two methods: context for fixed text, with_context with a closure when you format a path or id into the message.

for a middle

Explain that the message becomes the outer layer while the io::Error is stored as its source, and that context evaluates its argument eagerly while with_context defers it to the error path.

for a senior

Show where context belongs: at the layer that still knows the path, not at the top. Mention that downcast_ref still reaches the io::Error, so callers can branch on its kind.

for a principal

Frame context as a convention a codebase enforces: every fallible I/O call carries the resource it touched, so operators never see a bare os error 2 in production logs.

## Why the bare error is not enough When `std::fs::read_to_string` fails, it returns a `std::io::Error`. That type carries an **error kind** (`NotFound`, `PermissionDenied`, ...) and, for operating-system failures, the OS error code. It does **not** carry the path you passed in. Printed, it reads `No such file or directory (os error 2)`. In a deployment tool that loads a dozen manifest files, that message reaches the operator with no hint of *which* file was missing. Rust does not use exceptions for recoverable errors, and an `Err` carries no automatic record of the calls it passed through. Whatever a caller needs to know has to be put into the error value on its way up. That is what **context** means here: a human-readable layer, added at the point where the code still knows what it was trying to do. ## Adding context with the anyhow `Context` trait The `anyhow` crate provides an extension trait, `anyhow::Context`, implemented for `Result<T, E>` (where `E` is a std error that is `Send + Sync + 'static`, or already an `anyhow::Error`) and for `Option<T>`. It adds two methods: - **`context(msg)`** takes any value that implements `Display + Send + Sync + 'static` and wraps the error with it. - **`with_context(|| msg)`** takes a closure (`FnOnce() -> C`) and calls it only if the value is an `Err` or `None`. ```rust use anyhow::{Context, Result}; fn load_manifest(path: &std::path::Path) -> Result<String> { std::fs::read_to_string(path) .with_context(|| format!("failed to load manifest {}", path.display())) } ``` Three things happen in that call: 1. The `Result<String, io::Error>` becomes `Result<String, anyhow::Error>`, which is what `anyhow::Result<String>` means. 2. The new error's `Display` is your message, `failed to load manifest deploy/prod.toml`. 3. The original `io::Error` is stored **underneath** as the wrapped error's source, not discarded. Because it is a trait method, the trait must be in scope. Forgetting `use anyhow::Context;` gives error[E0599], "no method named `with_context` found for enum `Result<T, E>` in the current scope", and rustc's help line suggests the import. ## `context` vs `with_context` | | `context(msg)` | `with_context(closure)` | |---|---|---| | Argument | a value that is `Display + Send + Sync + 'static` | a closure returning such a value | | When the message is built | before the call, on every path, including `Ok` | only when the result is `Err` or `None` | | Best for | a fixed `&'static str` | `format!` with a path, id or other runtime data | The difference is ordinary Rust evaluation: an argument expression is evaluated before the method runs. `x.context(format!("loading {path}"))` allocates and formats a `String` even when the read succeeded; `with_context` defers that work to the failure path. ## What the wrapped error keeps - **The cause chain.** `err.chain()` yields your message, then the `io::Error`. Printing with `{:#}` gives `failed to load manifest deploy/prod.toml: No such file or directory (os error 2)`. - **Downcasting.** `err.downcast_ref::<std::io::Error>()` still returns `Some`, so code can check `kind() == NotFound` and decide what to do. anyhow documents that for an error with context, a downcast matches either the context type or the error it was attached to. - **A backtrace**, if backtraces are enabled through the environment; how that works is a separate topic. ## Mistakes that show up in review - Passing a closure to `context`: `.context(|| format!(...))` fails with `error[E0277]`, because a closure does not implement `Display`. Closures go to `with_context`. - Passing a borrow of a local: `.context(&msg)` where `msg` is a local `String` fails with error[E0597], "`msg` does not live long enough", because the message must be `'static`. Pass the `String` by value. - Re-typing the io error into the message string instead of wrapping it, which makes the source unreachable. - Adding context only at the top level, where the path is no longer known. Add it where the knowledge is. ## On `Option` The same trait turns `None` into an error: `config.get("host").context("no deploy host configured")?`. There is no source in that case; the message is the whole error, a chain of one. ## A short checklist for review 1. Every fallible file, network or parse call that can fail for an operator-visible reason carries the resource it touched: the path, the host, the record id. 2. Constant messages use `context`; messages built with `format!` use `with_context`. 3. The message describes what was being attempted (`failed to load manifest ...`) and does not repeat the cause, because the cause is printed separately when the chain is rendered. 4. Callers that branch on the cause use `downcast_ref` on the `anyhow::Error` rather than matching on the message text.

  • Why does `.context(|| format!("loading {path}"))` not compile?
    `context` takes the message itself, which must implement `Display + Send + Sync + 'static`. A closure does not implement `Display`, so rustc reports `error[E0277]` saying the closure doesn't implement `std::fmt::Display` and suggests calling it. A closure belongs in `with_context`, which accepts any `FnOnce() -> C` and calls it only on failure.
  • Can you pass `&msg`, a borrow of a local `String`, to `context`?
    No. The message type must be `'static` because the `anyhow::Error` may outlive the function. A `&String` borrowed from a local fails with error[E0597], "`msg` does not live long enough". Pass the `String` by value, a `&'static str` literal, or build it inside `with_context`.
  • What does `.context(...)` do on an `Option`?
    anyhow implements its `Context` trait for `Option<T>` too. `Some(v)` becomes `Ok(v)` and `None` becomes an `anyhow::Error` whose message is your context. There is no underlying cause in that case, so the chain has a single entry, which is fine for a missing configuration key.

  • Adding context replaces the io::Error, so its error kind is lost.
  • context and with_context behave the same; the closure is only a style choice.
  • with_context is an inherent method of Result, so no import is needed.
  • Passing a borrowed local string as the context message is fine because it is only printed.
  • Only a custom error enum can attach a file path to an io::Error.
open as a page

In a Rust payment library, why return Result<T, PaymentError> with an error enum instead of Result<T, String>?

level: juniorimportance: must knowfreq 68%

basics

~20 s

An error enum gives each failure a variant with its own data, so callers match on Declined, Network or InvalidCard instead of parsing text; rustc checks every variant is handled, and the enum can implement std::error::Error, which String does not.

open as a page

In Rust, when should a function return Option<T> and when should it return Result<T, E>?

level: juniorimportance: must knowfreq 78%

basics

~20 s

Return Option<T> when having no value is an ordinary outcome that needs no explanation, such as a map lookup; return Result<T, E> when the operation can fail and the caller needs to know why, such as parsing.

open as a page

In Rust, when should code panic instead of returning a Result, and why does indexing a Vec out of bounds panic?

level: juniorimportance: must knowfreq 75%

basics

~20 s

Panic when a bug has broken an invariant; return Result when failure is expected, like bad input or a lost connection. An out-of-bounds Vec index panics because it breaks the caller's contract and reading past the buffer is never allowed.

open as a page

In Rust, what does the `?` operator do when applied to a `Result`, and how is that different from calling `unwrap`?

level: juniorimportance: must knowfreq 82%

basics

~20 s

On Ok(v), the ? operator evaluates to v; on Err(e), it returns Err(From::from(e)) from the enclosing function at once. unwrap panics on Err instead, so ? hands a recoverable failure to the caller rather than crashing.

open as a page

In Rust, what decides whether std::backtrace::Backtrace::capture records a stack, and how do RUST_BACKTRACE and RUST_LIB_BACKTRACE differ?

level: middleimportance: must knowfreq 50%

basics

~20 s

Backtrace::capture checks RUST_LIB_BACKTRACE first, then RUST_BACKTRACE; a value of 0 disables it, any other value enables it, and neither set means disabled. The default panic hook reads only RUST_BACKTRACE, so RUST_LIB_BACKTRACE controls error backtraces separately.

open as a page

What must a Rust error enum implement to satisfy std::error::Error, and what does rustc report when Display is missing?

level: middleimportance: must knowfreq 62%

basics

~20 s

std::error::Error has Debug and Display as supertraits and gives every method a default, so derive Debug, write Display by hand and add an empty impl block; without Display, rustc stops with E0277: PaymentError doesn't implement std::fmt::Display.

open as a page

In Rust, when do you reach for thiserror and when for anyhow, and what does each give the code that receives the error?

level: middleimportance: must knowfreq 70%

basics

~20 s

thiserror derives std::error::Error for your own enum, so callers can match on its variants: the usual library choice. anyhow::Error wraps any error in one opaque type that is easy to propagate and print: the usual application choice.

open as a page

In Rust, why does Option::map with a closure that returns an Option give Option<Option<T>>, and how does and_then avoid it?

level: middleimportance: must knowfreq 65%

basics

~10 s

Option::map wraps whatever its closure returns in Some, so a closure returning Option<U> yields Option<Option<U>>. Option::and_then expects the closure to return Option<U> and returns it as is, giving a flat Option<U>.

open as a page

Why does rustc reject `text.trim().parse()?` with E0277 inside a Rust function returning `Result<u16, io::Error>`, and how do you fix it?

level: middleimportance: must knowfreq 68%

basics

~10 s

The ? operator converts the error with From::from, and std has no From<ParseIntError> for io::Error, so rustc reports E0277. Convert explicitly with map_err, or widen the error type, for example to Box<dyn Error>.

open as a page

In a Rust application using anyhow, what do bail! and ensure! do, and why can one function use ? on both io::Error and ParseIntError?

level: juniorimportance: should knowfreq 45%

basics

~20 s

bail!(...) returns early with Err(anyhow!(...)), and ensure!(cond, ...) does the same when cond is false. Both need a Result<_, anyhow::Error> return type. ? accepts both error types because anyhow::Error implements From for every std::error::Error + Send + Sync + 'static.

open as a page

When a Rust program prints an anyhow::Error, how do {}, {:#}, {:?} and {:#?} differ, and which does main use?

level: middleimportance: should knowfreq 45%

basics

~20 s

{} prints only the outermost message; {:#} prints every layer on one line joined by colons; {:?} prints a multi-line report with Caused by: and any captured backtrace; {:#?} is a struct-style dump. Returning Err from main prints Error: plus {:?}.

open as a page

In Rust, what does declaring pub enum PaymentError expose to downstream crates, and how should a variant wrap a dependency's error?

level: middleimportance: should knowfreq 38%

basics

~20 s

A pub enum makes every variant and every field public: callers can match, destructure and construct PaymentError, and each payload type joins your API. Keep a dependency's error out of it by storing it in a private field exposed only through source().

open as a page

In Rust, what does #[derive(thiserror::Error)] generate from #[error("...")] and #[from], and which uses of #[from] fail to compile?

level: middleimportance: should knowfreq 50%

basics

~10 s

The derive writes Display from each #[error("...")] string, std::error::Error with source() returning the #[from] or #[source] field, and one From impl per #[from] field. Two #[from] fields of one type conflict with E0119.

open as a page

In Rust, how do Option::ok_or, ok_or_else and Result::ok convert between Option and Result, and why prefer ok_or_else?

level: middleimportance: should knowfreq 52%

basics

~10 s

Option::ok_or(e) and ok_or_else(f) turn Some(v) into Ok(v) and None into Err; Result::ok() turns Ok(v) into Some(v) and drops the error. ok_or_else builds the error lazily, only when the Option is None.

open as a page

In Rust, what does std::panic::set_hook let a service do, when does the hook run, and how do you keep the default output?

level: middleimportance: should knowfreq 30%

basics

~20 s

set_hook replaces the single process-wide function std calls on every panic, on the panicking thread, before unwinding or aborting. Services use it to log panics their own way; calling take_hook first and forwarding to it keeps the default message.

open as a page

When a Rust thread panics, what does unwinding run, what changes under the abort strategy, and what does JoinHandle::join return?

level: middleimportance: should knowfreq 50%

basics

~20 s

By default a panic runs the panic hook, then unwinds the panicking thread, calling Drop on live values; join on that thread then returns Err. Under abort the hook runs and the whole process dies at once, without destructors.

open as a page

What happens when a Rust program whose `main` is declared `fn main() -> Result<(), Box<dyn Error>>` returns an `Err` through `?`?

level: middleimportance: should knowfreq 58%

basics

~20 s

Through std's Termination impl for Result, the runtime prints Error: followed by the error's Debug form to stderr and exits with ExitCode::FAILURE, status 1 on Unix and Windows. Locals in main are dropped normally first; nothing panics.

open as a page

In Rust, why can't `?` be applied to an `Option` inside a function that returns `Result`, and how do you bridge the two?

level: middleimportance: should knowfreq 55%

basics

~10 s

The ? operator on an Option can only return None, which a Result-returning function cannot return, so rustc reports E0277. Bridge explicitly: ok_or or ok_or_else makes a Result, and ok() makes an Option.

open as a page

A Rust service wraps I/O errors with map_err(|e| anyhow!("failed to load {path}: {e}")); why does downcast_ref::<io::Error>() now return None?

level: seniorimportance: should knowfreq 30%

basics

~20 s

anyhow! with a format string builds an error from the formatted text alone, so the io::Error is converted to a String and dropped. Its kind, code and place in the chain are gone; with_context(|| format!("failed to load {path}")) keeps it as the source.

open as a page

A Rust deploy tool logs each anyhow error at every layer before returning it with ?; why is that worse, and where should it log?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Logging and then returning with ? writes one fragment per layer, often with {} so the root cause never appears. Lower layers should only add context and propagate; the boundary that handles the error logs it once, with {:#} or {:?}.

open as a page

How do you recover a concrete PaymentError from a Rust Box<dyn Error + Send + Sync> with downcast_ref, and when does it return None?

level: seniorimportance: should knowfreq 35%

basics

~10 s

Call err.downcast_ref::<PaymentError>(), which checks whether the boxed value's concrete type is exactly PaymentError and returns Option<&PaymentError>; it returns None for any other type, including a wrapper whose source() is a PaymentError.

open as a page

Why does a Rust function returning Result<(), Box<dyn Error>> fail inside thread::spawn, and what does adding Send + Sync change?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A dyn Error trait object promises only Error, not Send, so the Result cannot leave a spawned thread and rustc reports E0277. Box<dyn Error + Send + Sync> admits only thread-safe errors, which spawn, Arc sharing and io::Error::new all need.

open as a page

How should a Rust PaymentError::Network variant expose its wrapped io::Error, and why should its Display not print it too?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Override source() to return Some of the io::Error for Network and None otherwise, and keep Display to PaymentError's own message: std's docs say a wrapped error belongs in source() or in Display, not both, or every report prints it twice.

open as a page

A Rust storage crate's public functions return anyhow::Result; what breaks for the web service calling it, and why doesn't anyhow::Error implement std::error::Error?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Callers lose typed matching: they must downcast_ref to an internal type, and that call keeps compiling after the crate stops producing it. anyhow::Error cannot implement std::error::Error because its blanket From would overlap core's impl<T> From<T> for T.

open as a page

In Rust, what happens when you collect an iterator of Result<T, E> into Result<Vec<T>, E>, and when is that the wrong choice?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Collecting into Result<Vec<T>, E> returns Ok with every value if all items are Ok, or the first Err; it stops pulling items at that Err. It is wrong when every failure must be reported or later items must still run.

open as a page

A Rust plugin host wraps each plugin call in std::panic::catch_unwind — what does that protect against, and which failures does it not catch?

level: seniorimportance: should knowfreq 25%

basics

~20 s

catch_unwind stops an unwinding panic and returns Err with the payload, so one buggy plugin does not take the host thread down. It catches nothing that aborts: panic=abort builds, a destructor panicking during unwinding, stack overflow, allocation failure.

open as a page

Inside a Rust closure, such as one passed to `Iterator::map`, why does `?` often fail to compile, and where does it return to when it does compile?

level: seniorimportance: should knowfreq 38%

basics

~20 s

The ? operator returns from the innermost closure, not the enclosing function, so the closure must return Result or Option. Otherwise rustc reports E0277; if the closure's error type cannot be inferred, E0282 until it is annotated.

open as a page

You lead a Rust workspace with a storage crate, a domain crate and a web service binary: what error strategy do you set across the crates, and where do errors convert?

level: principalimportance: should knowfreq 30%

basics

~20 s

Library crates return thiserror enums whose variants are the failures callers act on, wrapping dependency errors instead of exposing them. The binary uses anyhow internally and converts everything at one boundary type that decides the response.

open as a page

As the lead of a Rust service team, what policy would you set for unwrap, expect and panics in production code, and how would you enforce it?

level: principalimportance: should knowfreq 40%

basics

~20 s

Return Result for failures input, I/O or the network can cause; allow expect only for documented invariants with a should message; keep unwrap in tests; enforce with opt-in clippy lints; contain and log the panics that still ship.

open as a page

showing 1–30 of 32