Error Propagation With the Result Type

Return Result from functions and use the question-mark operator to propagate errors, keeping failure paths explicit and composable.

RustResilience

Code

rustsnippet
34 lines
use std::fs;
use std::io;
use std::num::ParseIntError;

#[derive(Debug)]
enum ConfigError {
    Io(io::Error),
    InvalidPort(ParseIntError),
}

impl From<io::Error> for ConfigError {
    fn from(error: io::Error) -> Self {
        ConfigError::Io(error)
    }
}

impl From<ParseIntError> for ConfigError {
    fn from(error: ParseIntError) -> Self {
        ConfigError::InvalidPort(error)
    }
}

fn read_port(path: &str) -> Result<u16, ConfigError> {
    let raw = fs::read_to_string(path)?;
    let port: u16 = raw.trim().parse()?;
    Ok(port)
}

fn main() {
    match read_port("port.txt") {
        Ok(port) => println!("port = {port}"),
        Err(error) => eprintln!("config error: {error:?}"),
    }
}

How it works

Error Propagation With the Result Type keeps everything in the functions from, read_port and main.

Fallible operations return Result, and the ? operator short-circuits errors up to the caller. A match spells out every case; omit one and the code does not compile.

Points of care

  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Using it

Signature: fn from(error: io::Error) -> Self

Running the file prints labeled results such as port = — each operation’s effect is visible in the output.

The entry point wires read_port together — run it once and the whole demo flows.

Key statements

fn read_port(path: &str) -> Result<u16, ConfigError> {
let raw = fs::read_to_string(path)?;
let port: u16 = raw.trim().parse()?;
Ok(port)
}
impl From<ParseIntError> for ConfigError {
fn from(error: ParseIntError) -> Self {
ConfigError::InvalidPort(error)
}
}
impl From<io::Error> for ConfigError {
fn from(error: io::Error) -> Self {
ConfigError::Io(error)
}
}

Interactive Tools for This Topic

FAQ

How are errors reported?
Through `Result` values propagated with the `?` operator. Nothing panics inside the snippet; the caller decides how to handle each failure.
What does Error Propagation With the Result Type print when run?
Run it as a complete program — the output lines carry labels such as `port =`.