Expand description
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))
}
Macros§
- try_
hard - The
try_soft
macro does the job of the?
operator: extract the SoftResult::Ok Value, without short-circuiting. It will short-circuit case or errors: - try_
soft - The
try_soft
macro does the job of the?
operator: extract the SoftResult::Ok Value, without short-circuiting. It will short-circuit in case of a SoftResult::SoftErr, returning aMalleableResult::Ok(SoftResult::SoftErr(_))
.
Enums§
- Soft
Result - A SoftResult, should only contain errors if these errors are benign, and can be presented to the user as a valid response.
Type Aliases§
- Malleable
Result - A hard result contains a hard error in its Err variant, and a SoftResult in its Ok variant. A hard error is a catastrophic failure, that should be avoided at all costs.