qubit_dcl/double_checked/callback_error.rs
1/*******************************************************************************
2 *
3 * Copyright (c) 2025 - 2026 Haixing Hu.
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0.
8 *
9 ******************************************************************************/
10//! # Callback Error
11//!
12//! Provides callback error information for double-checked execution.
13//!
14
15use std::fmt;
16
17/// Common error information for prepare lifecycle callbacks.
18///
19/// This keeps the error type name together with the message so callers can
20/// classify failures without depending on fragile string matching.
21///
22/// # Examples
23///
24/// ```rust
25/// use qubit_dcl::double_checked::CallbackError;
26///
27/// let prepare_error = CallbackError::with_type("prepare", "Resource is locked");
28/// assert_eq!(prepare_error.callback_type(), Some("prepare"));
29/// println!("prepare_error = {:?}", prepare_error);
30/// ```
31#[derive(Debug, Clone)]
32pub struct CallbackError {
33 /// Error message produced by the callback.
34 message: String,
35
36 /// Concrete type name, when available.
37 callback_type: Option<&'static str>,
38}
39
40impl CallbackError {
41 /// Builds a callback error without type metadata.
42 #[inline]
43 pub fn from_display<T: fmt::Display>(error: T) -> Self {
44 Self {
45 message: error.to_string(),
46 callback_type: None,
47 }
48 }
49
50 /// Builds a callback error with explicit callback type metadata.
51 #[inline]
52 pub fn with_type<T: fmt::Display>(source_type: &'static str, error: T) -> Self {
53 Self {
54 message: error.to_string(),
55 callback_type: Some(source_type),
56 }
57 }
58
59 /// Returns the raw message.
60 #[inline]
61 pub fn message(&self) -> &str {
62 &self.message
63 }
64
65 /// Returns the callback type label, when available.
66 #[inline]
67 pub fn callback_type(&self) -> Option<&'static str> {
68 self.callback_type
69 }
70
71 /// Returns whether the callback type label is set.
72 #[inline]
73 pub fn is_typed(&self) -> bool {
74 self.callback_type.is_some()
75 }
76}
77
78impl fmt::Display for CallbackError {
79 #[inline]
80 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81 match self.callback_type {
82 Some(callback_type) => write!(f, "{}: {}", callback_type, self.message),
83 None => write!(f, "{}", self.message),
84 }
85 }
86}