unwrap() panics instead of handling the error case
ID |
rust.correctness.unwrap_used |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Error Handling |
Language |
Rust |
Description
Reports a call to unwrap() on an Option or Result. Calls already guarded by an explicit is_some()/is_ok() test are left to the rule that reports the redundant check.
Rationale
unwrap() turns a None or an Err into an immediate panic, and it does so without a message, so the abort names only the source line and not the condition that caused it. A panic unwinds the current thread: in an async runtime or a request handler it takes down the task holding the work, and any lock it was holding is left poisoned for every other thread.
The following code illustrates the pattern detected by this rule:
use std::collections::HashMap;
fn port(env: &HashMap<String, String>) -> u16 {
// FLAGGED: unwrap() panics instead of handling the error case
let raw = env.get("PORT").unwrap();
// FLAGGED: unwrap() panics instead of handling the error case
raw.parse::<u16>().unwrap()
}