#![allow(clippy::unwrap_used)] //! Demonstrate every fallible API and recover from each error. //! //! Run with: `cargo run --example error_handling` //! //! Each panic-form (`new`, `lock_scope`, `claim`, `create`) has a //! paired `try_*` form returning a typed `Result<_, FooError>`. //! This example exercises every typed-error path so you can see //! the messages. use surelock::{ key::{lock_scope, try_lock_scope}, key_handle::{KeyHandle, error::ClaimError}, locksmith::{ Locksmith, error::{exists::LocksmithExistsError, issue::IssueError}, }, mutex::Mutex, set::{LockSet, error::LockSetError}, }; fn main() { // 1) LockSet::try_new on duplicate locks -> LockSetError::DuplicateLocks { let m: Mutex = Mutex::new(0); match LockSet::try_new((&m, &m)) { Ok(_) => unreachable!(), Err(e) => { assert_eq!(e, LockSetError::DuplicateLocks); println!("LockSet::try_new error: {e}"); } } } // 2) try_lock_scope while nested -> ClaimError::AlreadyClaimed lock_scope(|_outer| { let result = try_lock_scope(|_inner| 42); match result { Ok(_) => unreachable!("nested try_lock_scope must fail"), Err(e) => { assert_eq!(e, ClaimError::AlreadyClaimed); println!("try_lock_scope error: {e}"); } } }); // 3) KeyHandle::try_claim while claimed -> ClaimError::AlreadyClaimed { let _h = KeyHandle::claim(); match KeyHandle::try_claim() { Ok(_) => unreachable!(), Err(e) => { assert_eq!(e, ClaimError::AlreadyClaimed); println!("KeyHandle::try_claim error: {e}"); } } } // 4) Locksmith::new while one exists -> LocksmithExistsError::AlreadyExists { let _s = Locksmith::new(2).unwrap(); match Locksmith::new(2) { Ok(_) => unreachable!(), Err(e) => { assert_eq!(e, LocksmithExistsError::AlreadyExists); println!("Locksmith::new error: {e}"); } } } // 5) Locksmith::issue past limit -> IssueError::LimitReached { let s = Locksmith::new(1).unwrap(); let _v1 = s.issue().unwrap(); match s.issue() { Ok(_) => unreachable!(), Err(e) => { assert_eq!(e, IssueError::LimitReached); println!("Locksmith::issue error: {e}"); } } } println!("OK -- every error path is typed, matchable, and `Display`-friendly."); }