Skip to content
Select theme

Handling errors

Rust has no exceptions, so an error is a value you have to do something with. That is the whole idea; the rest is ergonomics — ?, map_err, From, and picking between a library’s thiserror and an application’s anyhow.

The last few articles are about panics, because knowing where they stop being acceptable is part of knowing when they are.

Nothing published in this chapter yet — all 27 articles are still to come.

Coming up (27)
  • How to return a Result from a functionthe signature, and what ? does inside it
  • How to use the ? operatorearly return, written as one character
  • How does ? work with both Option and Result?and why mixing them fails
  • How to unwrap an Option safelyfive ways, and when each is right
  • Why you should avoid unwrapthe panic you did not plan for
  • When is it okay to use unwrap and expect?prototypes, tests, and invariants
  • How to use unwrap_or and unwrap_or_defaultdefaults without branching
  • How to use map and and_then on Optiontransforming without unwrapping
  • How to use map_err on a Resultchanging the error type, not the value
  • How to combine several Resultscollect into a Result, and the first error wins
  • How to define a custom error typean enum with one variant per failure
  • How to implement the Error traitsource, Display, and what callers get
  • How to use thiserror to define error typesthe derive that writes the boilerplate
  • How to use anyhow in an applicationone error type that carries context
  • What is the difference between thiserror and anyhow?libraries versus applications
  • How to add context to an errorcontext(), and the message the user actually sees
  • How does the From trait make ? convert errors?the conversion you never wrote
  • How to handle errors in mainreturning Result, and what main prints
  • What are the valid return types of main?and what a returned Err actually does
  • When should you panic?the line between a bug and a failure
  • How to catch a paniccatch_unwind and the hooks around it
  • What is the difference between panic and Result?recoverable and not, decided up front
  • How to handle a “file not found” errormatching on ErrorKind instead of the message
  • How to handle parse errors gracefullyreport the input, not the parser
  • How to use ok_or and ok_or_else on Optionturning None into a real error
  • How to flatten nested Optionsflatten, and when the nesting means something
  • How to use Option as a function parameterand the argument against it