Error Handling with Rust Result

When a Rust function can fail, its caller may need to decide how to respond. Result gives the function a way to return either a successful value or an error.

I’ll show how to return and propagate errors with Result, then how to handle them at the caller.

TL;DR

Return Result<T, E> when an operation can fail, use ? to pass an unhandled error to the caller, and match on the result at the layer that can decide what to do.

  • Use Ok(value) for success and Err(error) for failure.
  • Use ? for early return, not to ignore an error.
  • Handle an error where there is a useful recovery or user-facing response.

What is Rust Result?

Result<T, E> is a standard-library enum for an operation that can succeed or fail. Its Ok(T) variant carries the success value, while Err(E) carries the error value, so callers can inspect either outcome.

Here, parsing uses u16 as T and ParseIntError as E.

Use match to inspect either variant:

match parse_port(input) { Ok(port) => println!(“Port: {port}”), Err(error) => eprintln!(“Invalid port: {error}”), }

The compiler checks both cases, so an added variant calls for another branch. This is useful when the error type grows because the caller must decide how the new case should be handled.

Rust marks Result as must_use, so ignoring one produces a compiler warning.

Use map to change a successful value while keeping Err unchanged. Use and_then when the next operation also returns Result.

A command-line caller can handle invalid input by asking for another value.

Use Option when absence is the expected outcome. Its None variant carries no error value. See CodeForGeek’s guide to Rust’s Option type for optional values.

How do you propagate errors with Result?

The receiving function’s return type must support the error or a conversion into its error type.

Step 1: Return a Result from fallible work

Give the function a Result return type and let the operation provide its concrete error type.

use std::num::ParseIntError; fn parse_port(input: &str) -> Result<u16, ParseIntError> { input.parse::<u16>() }

Parsing is fallible because the input may not represent a valid u16.

Step 2: Use ? to return an error early

Place the question-mark operator after a Result expression when this function should stop on Err. It yields the Ok value or returns the error from the current function.

fn load_port(input: &str) -> Result<u16, ParseIntError> { let port = parse_port(input)?; Ok(port) }

Step 3: Convert errors when a boundary needs one type

A boxed standard error combines different source errors at the boundary:

use std::error::Error; fn parse_port(input: &str) -> Result<u16, Box<dyn Error>> { Ok(input.parse::<u16>()?) }

The ? operator converts this parse error to the boxed error type. A named enum retains distinct cases for callers that need to match them.

Implement From only for infallible conversions. A conversion that can fail should return a Result.

A library’s error enum can be part of its public API. Callers may match its variants, so changing those cases can affect dependent code. A private command-line tool can choose a boxed error when callers only need to display or propagate it.

Rust’s Error::source() method can expose a lower-level cause for callers to inspect.

Step 4: Handle the result at the caller

The example’s main function is the program boundary, so it prints the success value or the parse error.

A small binary can give main a Result return type and use the question-mark operator to pass failures to the process boundary.

I compiled and ran result_demo.rs with the command shown in the terminal capture. The function propagates a parse error, and main handles the returned Result:

use std::num::ParseIntError; fn parse_port(input: &str) -> Result<u16, ParseIntError> { input.parse::<u16>() } fn load_port(input: &str) -> Result<u16, ParseIntError> { let port = parse_port(input)?; Ok(port) } fn main() { match load_port(“8080”) { Ok(port) => println!(“Listening on {port}”), Err(error) => println!(“Invalid port: {error}”), } }

The run printed this output:

Listening on 8080

The success branch received the port value after it crossed the function boundary. Changing the input to an invalid number follows the Err branch, which can print the parse error rather than panic.

Rust Result propagation example printing Listening on 8080

The terminal shows the source file’s compile command and its output.

When should you handle, propagate, or panic?

Use Err for operation failures a caller may respond to. A panic marks a violated assumption where continuing is unsafe.

SituationChoiceReason
Bad user input with a retry pathHandle ErrAsk for corrected input or return a validation message
Missing optional configHandle ErrUse a default only when the file is optional
Missing required configReturn or report ErrIdentify the missing path or setting
Library operation with no recovery contextPropagate with ?Let the caller decide how to respond
Broken assumption that should never occurConsider panicStop rather than continue in an invalid state

Retry only when an error suggests a temporary failure and the operation is safe to repeat. Check the operation’s result before repeating work that can cause side effects.

Unwrap and expect panic on Err. Expect adds a custom message, but both stop normal error propagation. Reserve them for tests or fixed invariants, not normal input or I/O failures.

For the enum mechanics behind Ok and Err, see CodeForGeek’s guide to Rust enums. The official Result documentation lists the standard methods and their behavior.

Conclusion

Preserve enough error detail for the caller to choose a useful response.

For the language’s full guidance, continue with the Rust Book’s chapter on recoverable errors and the standard library’s Result reference.

FAQ

These answers cover common decisions when a Rust function returns Result.

What does the ? operator do with Result?

It returns early from the current function when the value is Err, and otherwise yields the Ok value. The function must return a compatible Result type.

When should I use match instead of ??

Use match when the current function can choose a specific action for Ok and Err. Use ? when the error should return to the caller.

Is Result the same as Option?

No. Option represents a value that may be absent. Result represents success or failure and carries an error value in Err.

Aditya Gupta
Aditya Gupta

Aditya Gupta is a founding member and editor at CodeForGeek. He first found his way into tech by reading articles, and now writes approachable guides to Node.js security, authentication, AI tools, coding agents, and web scraping.

Articles: 529