14 / 35

Core Rust Concepts· 14 min read· Lesson 14 of 35

Error Handling with the ? Operator

Part 1 · Rust. Pass errors along cleanly with the ? operator, design your own error enum, and let main return a Result in your café ordering code.

In the last two lessons you handled every Option and Result with a full match. That’s safe, but when one task has several steps that can each fail, the matches pile up fast. Rust has a tiny operator that cleans this up: the question mark, ?. In this lesson we’ll use it to build a small, solid ordering function for the Rusty Bean Café.

The problem: match, match, match

Imagine taking an order from text a customer typed: an item name and a quantity. Several things can go wrong:

  1. The quantity isn’t a number.
  2. The item isn’t on the menu.

With only match, it looks like this:

src/main.rs
fn order_total(item: &str, quantity_text: &str) -> Result<u32, String> {
let quantity = match quantity_text.parse::<u32>() {
Ok(q) => q,
Err(_) => return Err(String::from("quantity must be a number")),
};
let price = match item {
"Latte" => 450,
"Mocha" => 475,
_ => return Err(format!("{item} is not on the menu")),
};
Ok(price * quantity)
}
fn main() {
println!("{:?}", order_total("Latte", "2"));
println!("{:?}", order_total("Latte", "two"));
}
Output
Ok(900)
Err("quantity must be a number")

It works. But notice the pattern: “if it’s Ok, take the value; if it’s Err, return the error right away”. We repeat that every time. ? does exactly this in one character.

The ? operator

Put ? after a Result and it means:

  • If it’s Ok(value), unwrap it and continue with value.
  • If it’s Err(e), return early from the current function with that error.

Café analogy: a barista working through a checklist. At each step, if something’s wrong (“out of milk”), they stop and pass the problem straight up to the manager instead of carrying on.

src/main.rs
use std::num::ParseIntError;
fn parse_quantity(text: &str) -> Result<u32, ParseIntError> {
let quantity = text.parse::<u32>()?;
Ok(quantity)
}
fn main() {
println!("{:?}", parse_quantity("3"));
println!("{:?}", parse_quantity("lots"));
}
Output
Ok(3)
Err(ParseIntError { kind: InvalidDigit })

Step by step:

  1. text.parse::<u32>() returns a Result<u32, ParseIntError>.
  2. The ? checks it. For "3" it hands back 3 and we continue.
  3. For "lots" it immediately returns Err(...) from parse_quantity. The Ok(quantity) line never runs.
  4. use std::num::ParseIntError; lets us name the error type in the function signature.

Important

? can only be used inside a function that itself returns a Result (or an Option). The error has to go somewhere, and that somewhere is your function’s return value.

If you forget, the compiler explains it clearly:

Output
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/main.rs:2:38
|
1 | fn main() {
| --------- this function should return `Result` or `Option` to accept `?`
2 | let quantity = "3".parse::<u32>()?;
| ^ cannot use the `?` operator in a function that returns `()`
|
help: consider adding return type
|
1 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
2 | let quantity = "3".parse::<u32>()?;
3 | println!("{quantity}");
4 + Ok(())
|

Read it from the bottom note: “cannot use ? in a function that returns ()”. () (pronounced “unit”) is what functions return when they don’t return anything. The fix is to change the return type. The help even suggests one, using a type called Box<dyn std::error::Error>, a general “any kind of error” box you’ll meet later. We’ll use our own error type for main at the end of this lesson.

Your own error enum

A String error is okay for quick code, but it’s hard for the caller to tell errors apart. Is it a typo, or are we out of stock? A better approach is an enum listing every way your task can fail. You already know enums from Enums and Match, so this will feel familiar.

src/main.rs
#[derive(Debug)]
enum OrderError {
BadQuantity(String),
UnknownItem(String),
OutOfStock { item: String, left: u32 },
}

Each variant is one kind of failure, carrying the details you’d want in a message. #[derive(Debug)] lets us print it with {:?}.

Turning other errors into yours with map_err and ok_or

Standard library functions return their error types, not ours. Two helpers convert them:

  • .map_err(|e| ...) changes the error inside an Err, leaving Ok alone.
  • .ok_or(error) turns an Option into a Result: Some(v) becomes Ok(v), and None becomes Err(error).

The |e| ... part is a closure, a small unnamed function. You’ll study closures properly later. For now, read |_| OrderError::BadQuantity(...) as “whatever the error was, replace it with this”.

Putting it together

src/main.rs
fn parse_quantity(text: &str) -> Result<u32, OrderError> {
text.parse::<u32>()
.map_err(|_| OrderError::BadQuantity(text.to_string()))
}
fn price_of(item: &str) -> Result<u32, OrderError> {
let price = match item {
"Latte" => Some(450),
"Croissant" => Some(325),
_ => None,
};
price.ok_or(OrderError::UnknownItem(item.to_string()))
}
fn check_stock(item: &str, wanted: u32, left: u32) -> Result<(), OrderError> {
if wanted > left {
return Err(OrderError::OutOfStock { item: item.to_string(), left });
}
Ok(())
}
fn place_order(item: &str, quantity_text: &str, stock: u32) -> Result<u32, OrderError> {
let quantity = parse_quantity(quantity_text)?;
let price = price_of(item)?;
check_stock(item, quantity, stock)?;
Ok(price * quantity)
}

(This goes in the same file as the OrderError enum above.)

Walking through place_order, the star of the show:

  1. parse_quantity(quantity_text)? either gives us a u32 or returns a BadQuantity error.
  2. price_of(item)? either gives us a price or returns UnknownItem.
  3. check_stock(...)? returns Result<(), OrderError>. On success there’s no useful value, just (), so we don’t store it. We only care that it didn’t fail.
  4. If we reach the last line, everything worked, and we return Ok(total).

Three possible failures, zero match statements, and it reads top to bottom like a recipe.

Handling the errors at the top

Somewhere, someone has to decide what to do with an error. Usually that’s near the top of the program, where we can show a friendly message:

src/main.rs
fn main() {
let orders = [("Latte", "2", 10), ("Latte", "two", 10), ("Pumpkin Pie", "1", 5), ("Croissant", "4", 3)];
for (item, qty, stock) in orders {
match place_order(item, qty, stock) {
Ok(total) => println!("{qty} x {item}: {total} cents"),
Err(OrderError::BadQuantity(text)) => println!("'{text}' isn't a number"),
Err(OrderError::UnknownItem(name)) => println!("Sorry, no {name} today"),
Err(OrderError::OutOfStock { item, left }) => {
println!("Only {left} {item} left")
}
}
}
}
Output
2 x Latte: 900 cents
'two' isn't a number
Sorry, no Pumpkin Pie today
Only 3 Croissant left

Because OrderError is an enum, match makes us handle every kind of failure, and gives each one its own friendly message.

Tip

A good rule of thumb: low-level functions use ? to pass errors up. The top level (like main, or later a web request handler) decides what to show the user.

main can return a Result too

For small programs, you can let main itself return a Result. Then you can use ? directly inside main:

src/main.rs
fn main() -> Result<(), OrderError> {
let total = place_order("Latte", "3", 10)?;
println!("Total: {total} cents");
let total = place_order("Unicorn Frappe", "1", 10)?;
println!("Total: {total} cents"); // never reached
Ok(())
}
Output
Total: 1350 cents
Error: UnknownItem("Unicorn Frappe")
  1. The return type Result<(), OrderError> means “nothing useful on success, an OrderError on failure”.
  2. The first order works and prints.
  3. The second ? hits an Err, so main returns early.
  4. Rust prints Error: followed by the debug form of the error, and the program exits with a non-zero exit code, the standard way programs tell the terminal “something went wrong”.
  5. Ok(()) at the end means “everything finished fine”.

Note

For main to return your error type, the type needs #[derive(Debug)], because that’s how Rust prints it. That’s one more reason to derive Debug on your error enums. In this version the compiler also warns that the data inside all three variants is never read: the text in BadQuantity, the text in UnknownItem, and the item and left fields of OutOfStock. Printing with Debug doesn’t count as reading them. It’s only a warning, and it goes away once some code (like the match in the previous section) uses that data.

Warning

? is not a way to ignore errors. It passes them on. If every function, including main, just uses ?, the user still sees a raw debug message. Make sure some level of your program turns errors into helpful messages.

A shortcut: your own Result alias

Writing Result<u32, OrderError> again and again gets repetitive when every function in a file uses the same error type. Rust lets you give a type a shorter nickname with a type alias, using the type keyword:

src/main.rs
#[derive(Debug)]
enum OrderError {
UnknownItem(String),
}
type Result<T> = std::result::Result<T, OrderError>;
fn price_of(item: &str) -> Result<u32> {
match item {
"Latte" => Ok(450),
"Bagel" => Ok(350),
_ => Err(OrderError::UnknownItem(item.to_string())),
}
}
fn main() -> Result<()> {
let bagel = price_of("Bagel")?;
println!("Bagel: {bagel} cents");
if let Err(OrderError::UnknownItem(name)) = price_of("Smoothie") {
println!("No {name} on the menu");
}
Ok(())
}
Output
Bagel: 350 cents
No Smoothie on the menu
  1. type Result<T> = std::result::Result<T, OrderError>; creates a nickname. From now on in this file, Result<u32> means std::result::Result<u32, OrderError>.
  2. std::result::Result is the full name of the normal, built-in Result. We spell it out so the alias doesn’t refer to itself.
  3. fn price_of(...) -> Result<u32> now needs only one type: the success type. The error type is filled in for you.
  4. main returns Result<()> the same way, and ? works exactly as before.

Nothing new is happening underneath. A Result with one type parameter is still the very same Result with Ok and Err, just with the error type pre-filled. Libraries and frameworks do this all the time. When you get to Laravel Rust you’ll see signatures like laravel::Result<()>: that’s the framework’s own alias, with its error type already chosen.

Try it yourself

  1. Add a new variant TooLarge(u32) to OrderError. Change parse_quantity so that, after parsing, a quantity above 20 returns Err(OrderError::TooLarge(quantity)). Use ? for the parse step.
Show solution
fn parse_quantity(text: &str) -> Result<u32, OrderError> {
let quantity = text
.parse::<u32>()
.map_err(|_| OrderError::BadQuantity(text.to_string()))?;
if quantity > 20 {
return Err(OrderError::TooLarge(quantity));
}
Ok(quantity)
}

Don’t forget to add a TooLarge arm to the match in main. The compiler will remind you if you do forget.

  1. Loyalty stamps aren’t cups of coffee, so the 20-cup limit from exercise 1 shouldn’t apply to them. Write a small parse_stamps(text: &str) -> Result<u32, OrderError> that parses the text with no upper limit (reuse the BadQuantity variant for text that isn’t a number). Then write fn loyalty_discount(stamps_text: &str) -> Result<u32, OrderError> that calls parse_stamps with ? and returns Ok(50) (50 cents off) for 10 or more stamps, otherwise Ok(0). Test it with "25", "4" and "lots".
Show solution
src/main.rs
#[derive(Debug)]
enum OrderError {
BadQuantity(String),
}
fn parse_stamps(text: &str) -> Result<u32, OrderError> {
text.parse::<u32>()
.map_err(|_| OrderError::BadQuantity(text.to_string()))
}
fn loyalty_discount(stamps_text: &str) -> Result<u32, OrderError> {
let stamps = parse_stamps(stamps_text)?;
if stamps >= 10 { Ok(50) } else { Ok(0) }
}
fn main() {
for text in ["25", "4", "lots"] {
match loyalty_discount(text) {
Ok(cents) => println!("{text} stamps: {cents} cents off"),
Err(OrderError::BadQuantity(bad)) => println!("'{bad}' isn't a number of stamps"),
}
}
}
Output
25 stamps: 50 cents off
4 stamps: 0 cents off
'lots' isn't a number of stamps

To keep this solution short and runnable on its own, the enum here has only BadQuantity. In your full program, keep all your variants and add the other arms to the match. Giving stamps their own parser means 25 stamps is perfectly fine, even though 25 cups would be TooLarge.

Recap

  • ? after a Result means “give me the Ok value, or return the Err from this function right now”.
  • You can only use ? inside functions that return Result (or Option).
  • A custom error enum lists every way a task can fail, so callers can match on each one.
  • .map_err(...) and .ok_or(...) convert other errors and Options into your error type.
  • main can return Result<(), YourError>, which lets you use ? there too.

What’s next

You’ve finished Core Rust! Next up is the Rust Next Level module, starting with Traits and Generics, where you’ll learn how to write code that works for many types at once.

0 of 35 lessons complete

Search lessons

Type to search all lessons.