Skip to main content

error_kernel/
error_kernel.rs

1//! Implement the `DomainError` contract for a custom error type and inspect the
2//! shared classification (HTTP status, retryability, stable code).
3//!
4//! Run with: `cargo run -p klauthed-error --example error_kernel`
5
6use klauthed_error::{DomainError, ErrorCategory, ErrorCode};
7
8#[derive(Debug)]
9enum OrderError {
10    NotFound,
11    PaymentDeclined,
12    LedgerUnavailable,
13}
14
15impl std::fmt::Display for OrderError {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        match self {
18            OrderError::NotFound => f.write_str("order not found"),
19            OrderError::PaymentDeclined => f.write_str("payment was declined"),
20            OrderError::LedgerUnavailable => f.write_str("ledger service is unavailable"),
21        }
22    }
23}
24
25impl std::error::Error for OrderError {}
26
27impl DomainError for OrderError {
28    fn category(&self) -> ErrorCategory {
29        match self {
30            OrderError::NotFound => ErrorCategory::NotFound,
31            OrderError::PaymentDeclined => ErrorCategory::UnprocessableEntity,
32            OrderError::LedgerUnavailable => ErrorCategory::Unavailable,
33        }
34    }
35
36    fn code(&self) -> ErrorCode {
37        match self {
38            OrderError::NotFound => ErrorCode::new("order.not_found"),
39            OrderError::PaymentDeclined => ErrorCode::new("order.payment_declined"),
40            OrderError::LedgerUnavailable => ErrorCode::new("order.ledger_unavailable"),
41        }
42    }
43}
44
45fn main() {
46    let errors = [OrderError::NotFound, OrderError::PaymentDeclined, OrderError::LedgerUnavailable];
47
48    println!("{:<32} {:<28} {:>4}  retryable", "error", "code", "http");
49    for err in &errors {
50        let code = err.code();
51        println!(
52            "{err:<32} {:<28} {:>4}  {}",
53            code.as_str(),
54            err.http_status(),
55            err.is_retryable(),
56        );
57    }
58}