Skip to main content

Crate unwrap_safe

Crate unwrap_safe 

Source
Expand description

Safe unwrap replacements that log instead of panic.

.unwrap() and .expect() are useful during development but cause production outages when invariants break. This crate provides drop-in macro replacements that degrade gracefully: return a default value and emit a structured log instead of panicking.

§Quick Reference

BeforeAfterFor
opt.unwrap()unwrap_or_warn!(opt, default, "ctx")Option<T>
res.unwrap()result_or_warn!(res, default, "ctx")Result<T, E>
s.parse::<T>().unwrap()parse_or_warn!(s, T, default, "ctx")String parsing
opt.expect("msg")expect_or_error!(opt, default, "msg")Option soft-expect
res.expect("msg")expect_result_or_error!(res, default, "msg")Result soft-expect

All macros include file!() and line!() in the log output.

§Example

use unwrap_safe::{unwrap_or_warn, result_or_warn, parse_or_warn};

// Option: return default on None
let name: Option<String> = None;
let display = unwrap_or_warn!(name, String::from("anonymous"), "user display name");
assert_eq!(display, "anonymous");

// Result: return default on Err
let val: Result<i32, String> = Err("timeout".into());
let count = result_or_warn!(val, 0, "request count");
assert_eq!(count, 0);

// Parse: return default on bad input
let port = parse_or_warn!("not_a_port", u16, 8080, "PORT env var");
assert_eq!(port, 8080);

Macros§

expect_or_error
Soft expect for Option: logs an error and returns a default instead of panicking.
expect_result_or_error
Soft expect for Result: logs an error and returns a default instead of panicking.
parse_or_warn
Parse a string into a type, returning a default and logging on failure.
result_or_warn
Unwrap a Result<T, E>, returning a default and logging a warning on Err.
unwrap_or_warn
Unwrap an Option<T>, returning a default and logging a warning if None.