rust.unsafe_unwrap
Stability
High
Common in Incidents
Detects .unwrap() calls on Result/Option that could panic in production, with smart pattern detection for idiomatic fixes.
Why It Matters
Section titled “Why It Matters”.unwrap() panics when the value is Err or None:
- Production crashes — Panics bring down the entire thread or task
- Async runtime crashes — In Tokio, panics in tasks can crash workers
- No error context — Panic message doesn’t explain what went wrong
- Hidden assumptions — Assumes infallibility without documenting why
Rust’s type system exists to prevent these errors. Use it.
Example
Section titled “Example”// ❌ Beforefn process(data: Option<String>) -> String { data.unwrap() // Will panic if None}
fn read_file() -> Config { let content = std::fs::read_to_string("config.toml").unwrap(); toml::from_str(&content).unwrap()}// ✅ Afterfn process(data: Option<String>) -> Result<String, Error> { data.ok_or(Error::MissingData)}
fn read_file() -> Result<Config, Error> { let content = std::fs::read_to_string("config.toml") .map_err(|e| Error::ConfigRead(e))?; toml::from_str(&content) .map_err(|e| Error::ConfigParse(e))}What Unfault Detects
Section titled “What Unfault Detects”.unwrap()onResultorOption.expect()in library code.unwrap_or_default()where default might not make sense- Chained unwraps like
x.y.unwrap().z.unwrap()
Auto-Fix
Section titled “Auto-Fix”Unfault can convert .unwrap() to ? operator or .ok_or() with appropriate error types when the function signature supports it.
When Unwrap Is Acceptable
Section titled “When Unwrap Is Acceptable”// Tests - panics are expected behavior#[test]fn test_something() { let result = function().unwrap();}
// Static guarantees - compiler can prove it won't paniclet num: u32 = "42".parse().unwrap(); // But still better to const
// Initialization - fail fast on startuplazy_static! { static ref CONFIG: Config = load_config().unwrap();}Better Alternatives
Section titled “Better Alternatives”// ? operator - propagate errorsfn foo() -> Result<T, E> { let x = fallible()?; Ok(x)}
// ok_or - convert Option to Resultlet value = option.ok_or(Error::Missing)?;
// unwrap_or - provide defaultlet value = option.unwrap_or_else(|| default());
// if let / match - handle explicitlyif let Some(value) = option { use_value(value);}