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:
- The quantity isn’t a number.
- The item isn’t on the menu.
With only match, it looks like this:
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"));}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 withvalue. - 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.
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"));}Ok(3)Err(ParseIntError { kind: InvalidDigit })Step by step:
text.parse::<u32>()returns aResult<u32, ParseIntError>.- The
?checks it. For"3"it hands back3and we continue. - For
"lots"it immediately returnsErr(...)fromparse_quantity. TheOk(quantity)line never runs. 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:
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.
#[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 anErr, leavingOkalone..ok_or(error)turns anOptioninto aResult:Some(v)becomesOk(v), andNonebecomesErr(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
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:
parse_quantity(quantity_text)?either gives us au32or returns aBadQuantityerror.price_of(item)?either gives us a price or returnsUnknownItem.check_stock(...)?returnsResult<(), OrderError>. On success there’s no useful value, just(), so we don’t store it. We only care that it didn’t fail.- 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:
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") } } }}2 x Latte: 900 cents'two' isn't a numberSorry, no Pumpkin Pie todayOnly 3 Croissant leftBecause 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:
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(())}Total: 1350 centsError: UnknownItem("Unicorn Frappe")- The return type
Result<(), OrderError>means “nothing useful on success, anOrderErroron failure”. - The first order works and prints.
- The second
?hits anErr, somainreturns early. - 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”. 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:
#[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(())}Bagel: 350 centsNo Smoothie on the menutype Result<T> = std::result::Result<T, OrderError>;creates a nickname. From now on in this file,Result<u32>meansstd::result::Result<u32, OrderError>.std::result::Resultis the full name of the normal, built-inResult. We spell it out so the alias doesn’t refer to itself.fn price_of(...) -> Result<u32>now needs only one type: the success type. The error type is filled in for you.mainreturnsResult<()>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
- Add a new variant
TooLarge(u32)toOrderError. Changeparse_quantityso that, after parsing, a quantity above20returnsErr(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.
- 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 theBadQuantityvariant for text that isn’t a number). Then writefn loyalty_discount(stamps_text: &str) -> Result<u32, OrderError>that callsparse_stampswith?and returnsOk(50)(50 cents off) for 10 or more stamps, otherwiseOk(0). Test it with"25","4"and"lots".
Show solution
#[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"), } }}25 stamps: 50 cents off4 stamps: 0 cents off'lots' isn't a number of stampsTo 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 aResultmeans “give me theOkvalue, or return theErrfrom this function right now”.- You can only use
?inside functions that returnResult(orOption). - A custom error enum lists every way a task can fail, so callers can
matchon each one. .map_err(...)and.ok_or(...)convert other errors andOptions into your error type.maincan returnResult<(), 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