Expand description
Tiny bailing convenience macros.
Bailing is an error-handling pattern that takes the middle path between unwrap and ?:
- Compared to
unwrap: Bailing willreturn,continue, orbreakinstead of panicking. - Compared to
?: Bailing will log or discard the error instead of returning it.
The middle path avoids unwanted panics without the ergonomic challenges of propagating errors with ?.
This crate provides the following macro variants to determine the preferred behavior on failure:
or_return!or_return_quiet!or_return_log_once!or_continue!or_continue_quiet!or_continue_log_once!or_break!or_break_quiet!or_break_log_once!
Along with their tiny aliases:
r!,
rq!,
ro!,
c!,
cq!,
co!,
b!,
bq!, and
bo!.
The macros support Result, Option, and bool types out of the box.
Implement IntoResult to extend this to other types.
§Example
use tiny_bail::prelude::*;
// With `tiny_bail`:
fn increment_last(arr: &mut [i32]) {
*r!(arr.last_mut()) += 1;
}
// Without `tiny_bail`:
fn increment_last_manually(arr: &mut [i32]) {
if let Some(x) = arr.last_mut() {
*x += 1;
} else {
println!("Bailed at src/example.rs:34:18: `arr.last_mut()`");
return;
}
}§Getting started
To use this crate, add it to your Cargo.toml:
cargo add tiny_bailYou can set features to customize the logging behavior on bail:
# Log with `println!` instead of `tracing::warn!`.
cargo add tiny_bail --no-default-features
# Log with `log::info!` instead of `tracing::warn!`.
cargo add tiny_bail --no-default-features --features log,infoThis crate has zero dependencies other than the logging backend you choose (log, tracing, or nothing).
Modules§
Macros§
- or_
break - Unwrap on success, or log the failure and break.
- or_
break_ log_ once - Unwrap on success, or log the first failure and break.
- or_
break_ quiet - Unwrap on success, or quietly discard the failure and break.
- or_
continue - Unwrap on success, or log the failure and continue.
- or_
continue_ log_ once - Unwrap on success, or log the first failure and continue.
- or_
continue_ quiet - Unwrap on success, or quietly discard the failure and continue.
- or_
return - Unwrap on success, or log the failure and return.
- or_
return_ log_ once - Unwrap on success, or log the first failure and return.
- or_
return_ quiet - Unwrap on success, or quietly discard the failure and return.
Traits§
- Into
Result - A trait for types that can be separated into success and failure values.