Project Quality · 18 min · free lesson

Error Context

Preserve a cause while explaining the failed operation.

Core idea

A useful error says what operation failed and retains the original cause.

Diagram for Error Context: a Rust code example flows to the lesson rule and the key observation.
map_err adds the operation and the value, and keeps the parser's message in the text.

Understand it

A useful error says what operation failed and retains the original cause. Add context at abstraction boundaries rather than replacing specific information with one vague message.

An error should carry enough information for someone at the boundary to understand what failed. text.parse::<u16>() can report a parsing failure, but a caller may need to know that this text was supposed to be a port. The example's map_err adds the offending value and the operation while preserving the underlying cause in the formatted message. At a higher layer, you might add which configuration file or command supplied that value.

The useful question is where to add context. A low-level parser knows syntax; a configuration loader knows the field name; a CLI knows what the user was trying to do. Each layer should add only the information it owns. Replacing every error with the same "invalid input" string erases evidence. Duplicating full messages at every layer produces noise. Structured error types or source chains can preserve machine-readable causes until the final presentation layer chooses wording.

Try the port function with valid text, letters, and a number too large for u16. Check that the user-facing message distinguishes where the failure occurred without exposing irrelevant internal details. If recovery is possible, return Result so the caller can decide. If the error is logged, include enough context to reproduce it while avoiding secrets or full sensitive input. Good diagnostics are a collaboration between error type, call-site context, and final display—not a single catch-all message.

Read the code

fn port(text: &str) -> Result<u16, String> {
    text.parse().map_err(|error| {
        format!("invalid port {text}: {error}")
    })
}

map_err adds the operation and the value, and keeps the parser's message in the text.

Practice starter

fn port(text: &str) -> Result<u16, String> {
    text.parse().map_err(|_| {
        "invalid input".to_string()
    })
}

Practise this code in Playground ↗

Try it

Call this port with abc and with 99999, then compare the two messages. Rewrite the map_err so each one says which value failed and why.

What success looks like: Both failures name the value and keep the parser's own reason.

Check your understanding

What should context preserve?

Reveal the answer
  1. The original cause
  2. Only a short label
  3. A stack address

Context should add what the caller was doing without losing why it failed, so keep the parser's error in the message or as a source.

Go deeper

Common misconception: “Replacing a low-level error with one clear message is the same as adding context.”

A useful error says what operation failed and retains the original cause. “invalid input” hides both the value and the reason.

  1. Try the parse: text.parse() infers u16 from the return type, so 8080 gives Ok(8080) and the map_err closure never runs.
  2. Hit the failure: For abc, parse returns Err, and map_err runs its closure with the ParseIntError as error.
  3. Read the message: format! produces invalid port abc: invalid digit found in string, so the text carries both the operation and the cause.

Transfer challenge: Replace the String with an enum that holds the ParseIntError, and implement Display and Error::source. Predict what a caller can now do that a formatted string did not allow.

Connections

  • Integration Tests: Test the public API as an outside user
  • Executable Documentation: Keep API examples checked by the test suite
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Error Context (courseId "projects", lessonId "error-context")
Link: https://crabrix.com/learn/projects/error-context/
Goal: A useful error says what operation failed and retains the original cause.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=projects/error-context) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.