Error Handling
Propagate and transform failures with Result, Option, and the ? operator. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Busca en todas las páginas de la documentación
Propagate and transform failures with Result, Option, and the ? operator. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
? returns early on Err / None (in Option context).
fn parse(s: &str) -> Result<i32, std::num::ParseIntError> {
Ok(s.parse()?)
}
parse("12").unwrap() // 12Transform error types while keeping Ok.
fn go(s: &str) -> Result<i32, String> {
s.parse::<i32>().map_err(|e| e.to_string())
}
go("x").unwrap_err().contains("invalid") // trueLift Option into Result with an error value.
None::<i32>.ok_or("missing").unwrap_err() // "missing"
Some(1).ok_or("missing").unwrap() // 1Panic on failure - fine in examples, rare in libraries.
Some(3).unwrap() // 3
Some(3).expect("need value") // 3Provide a fallback without panicking.
None::<i32>.unwrap_or(0) // 0
"x".parse::<i32>().unwrap_or(-1) // -1Sequence fallible steps.
Some(2).and_then(|n| Some(n * 3)) // Some(6)Transform success without touching Err.
Ok::<_, ()>(2).map(|n| n + 1) // Ok(3)Domain errors as enums with Display/Error.
#[derive(Debug)]
enum E { NotFound, Bad }
impl std::fmt::Display for E {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{self:?}")
}
}
format!("{}", E::NotFound) // "NotFound"? uses From to convert error types.
fn inner() -> Result<(), String> { Err("e".into()) }
fn outer() -> Result<(), String> { Ok(inner()?) }
outer().unwrap_err() // "e"Collect iterator of Results into one Result.
let xs: Result<Vec<_>, _> = ["1", "2"].iter().map(|s| s.parse::<i32>()).collect();
xs.unwrap() // [1, 2]In apps, crates like anyhow add context chains - pattern: attach context on ?.
// anyhow::Context::context(result, "loading config")
// keeps error cause chain for operatorsLibrary errors often use thiserror for Display/From derives.
// #[derive(thiserror::Error, Debug)]
// enum E { #[error("not found")] NotFound }panic! aborts the current thread path; prefer Result in APIs.
// panic!("bug"); // unwinds or aborts depending on profileType aliases shorten repeated Result signatures.
type R<T> = Result<T, String>;
fn f() -> R<i32> { Ok(1) }
f().unwrap() // 1Debug side effects without consuming Result (nightly/inspect_err or match).
let r: Result<i32, &str> = Err("x");
match &r {
Err(e) => *e, // "x"
Ok(_) => "",
}Stack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Revisado por Chris St. John·Última actualización: 19 jul 2026