
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()
})
}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
- The original cause
- Only a short label
- 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.
- Try the parse:
text.parse()infersu16from the return type, so8080givesOk(8080)and themap_errclosure never runs. - Hit the failure: For
abc,parsereturnsErr, andmap_errruns its closure with theParseIntErroraserror. - Read the message:
format!producesinvalid 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.