2 releases
Uses new Rust 2024
new 0.1.1 | Apr 11, 2025 |
---|---|
0.1.0 | Apr 11, 2025 |
#6 in #try
8KB
74 lines
Look at https://docs.rs/try_hard/ in docs.rs!
lib.rs
:
Provides the [MalleableResult] and [SoftResult] types, and the [try_hard] and [try_soft] macros.
Support the tracing
crate!
A [MalleableResult] distinguishes errors in two categories:
-
Soft errors: These are "benign" error types that shouldn't cause your application to stop. Think of 404 errors, or any other error that was caused by the user, and not by your application. Soft errors won't trigger
error
events when used with the#[instrument(err)]
tracing
macro. -
Hard errors: These are bad. Hard errors are in general not fault of the user, and the user is hopeless without our intervention. Hard errors must be monitored. Hard errors will result in
error
events when used with the#[instrument(err)]
tracing macro.
How can I use it?
use tracing::instrument;
use try_hard::*;
struct ValidName(String);
struct User {
id: u64,
name: ValidName,
}
#[derive(Debug, thiserror::Error)]
#[error("scary database failure")]
struct DatabaseFailure;
#[derive(Debug)]
struct InvalidNameError(String);
fn fetch_user(name: &ValidName) -> Result<User, DatabaseFailure> {
todo!()
}
#[instrument]
fn validate_name(name: &str) -> SoftResult<ValidName, InvalidNameError> {
if name.contains("💩") {
return SoftResult::SoftErr(InvalidNameError("name contains 💩 emoji".to_string()))
}
SoftResult::Ok(ValidName(name.to_string()))
}
#[instrument(err)]
fn locate_user_in_db(name: &str) -> MalleableResult<User, InvalidNameError, DatabaseFailure> {
let valid_name = try_soft!(validate_name(name));
let user = fetch_user(&valid_name)?;
Ok(SoftResult::Ok(user))
}
#[instrument(err)]
fn inside_your_application(
name: &str
) -> MalleableResult<User, InvalidNameError, DatabaseFailure> {
let user = try_hard!(locate_user_in_db(name));
Ok(SoftResult::Ok(user))
}