Main Returning Result With Box Dyn Error

Return Result from main with Box<dyn Error> so ? converts std errors and string messages, and failures exit the process non-zero.

RustResilience

Code

rustsnippet
21 lines
use std::error::Error;

fn parse_port(raw: &str) -> Result<u16, Box<dyn Error>> {
    // ParseIntError 自动转成 Box<dyn Error>
    let port: u16 = raw.trim().parse()?;
    if port < 1024 {
        // &str 错误消息同样能转
        return Err("privileged port refused".into());
    }
    Ok(port)
}

fn main() -> Result<(), Box<dyn Error>> {
    let port = parse_port("8443")?;
    println!("serving on port {}", port);

    // 失败直接交给 main:返回 Err 时进程以非零码退出并打印错误
    let forced = parse_port("http")?;
    println!("unreachable: {}", forced);
    Ok(())
}

How the snippet works

Main Returning Result With Box Dyn Error comes down to the functions parse_port and main.

Result is the error channel: the caller receives the failure as a value instead of an exception.

Points of care

  • Result is the only error channel — remove a ? while adapting and that site needs an explicit match.

Using it

The main signature reads fn parse_port(raw: &str) -> Result<u16, Box<dyn Error>>

The demo output is labeled (serving on port, unreachable:), so every printed line maps back to its originating operation.

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

Key statements

fn parse_port(raw: &str) -> Result<u16, Box<dyn Error>> {
// ParseIntError 自动转成 Box<dyn Error>
let port: u16 = raw.trim().parse()?;
if port < 1024 {
// &str 错误消息同样能转
return Err("privileged port refused".into());
}
Ok(port)
}
fn main() -> Result<(), Box<dyn Error>> {
let port = parse_port("8443")?;
println!("serving on port {}", port);
// 失败直接交给 main:返回 Err 时进程以非零码退出并打印错误
let forced = parse_port("http")?;
println!("unreachable: {}", forced);
Ok(())
}

Interactive Tools for This Topic

FAQ

How should callers handle failures?
As data, not exceptions: `Result` makes the caller handle both arms.
What does Main Returning Result With Box Dyn Error print when run?
Invoke the file as-is — the `serving on port`, `unreachable:` prefixes identify which step printed each line.