Fall Back Through Sources With Or Else

Chain Result-returning config sources with or_else so each fallback runs only when the previous source failed, and every error message accumulates.

RustResilience

Code

rustsnippet
28 lines
/// 每个 source 返回 Result:失败信息里带上来源名,便于归因
fn port_from_env() -> Result<u16, String> {
    Err("env PORT not set".into())
}

fn port_from_file() -> Result<u16, String> {
    Err("config.toml missing".into())
}

fn port_from_flag() -> Result<u16, String> {
    Ok(9090)
}

fn main() {
    // or_else 只在上一个来源 Err 时才执行闭包:前两个失败后,第三个才被调用
    let port = port_from_env()
        .or_else(|env_err| {
            port_from_file().map_err(|file_err| format!("{env_err}; {file_err}"))
        })
        .or_else(|errs| {
            port_from_flag().map_err(|flag_err| format!("{errs}; {flag_err}"))
        });

    match port {
        Ok(value) => println!("resolved port: {value}"),
        Err(all) => println!("no source worked: {all}"),
    }
}

How it works

Structurally, expect the functions port_from_env, port_from_file, port_from_flag and main and nothing else.

Fallible operations return Result, forcing the caller to handle both arms explicitly. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

What to watch for

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

Applying it

The entry-point signature is fn port_from_env() -> Result<u16, String>

Output lines are prefixed (resolved port:, no source worked:), making each step’s effect easy to spot.

Running the file executes main, which drives port_from_env, port_from_file and port_from_flag in order.

Statements that matter

fn port_from_file() -> Result<u16, String> {
    Err("config.toml missing".into())
}
fn port_from_flag() -> Result<u16, String> {
    Ok(9090)
}
fn port_from_env() -> Result<u16, String> {
    Err("env PORT not set".into())
}

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
No panics — `Result` values carry the failure.
What does Fall Back Through Sources With Or Else print when run?
Running the file directly is enough — expect labeled output lines such as `resolved port:`, `no source worked:`.