Skip to main content

qubit_progress/error/
reporter_error.rs

1// =============================================================================
2//    Copyright (c) 2025 - 2026 Haixing Hu.
3//
4//    SPDX-License-Identifier: Apache-2.0
5//
6//    Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Errors returned directly by reporter sinks.
9// qubit-style: allow source-test-pair
10
11use std::error::Error;
12use std::fmt;
13use std::sync::Arc;
14
15/// Reporter failure that preserves its original error chain.
16#[derive(Clone, Debug)]
17pub struct ReporterError {
18    source: Arc<dyn Error + Send + Sync + 'static>,
19}
20
21impl ReporterError {
22    /// Wraps a concrete reporter failure without discarding its source.
23    pub fn new<E>(source: E) -> Self
24    where
25        E: Error + Send + Sync + 'static,
26    {
27        Self {
28            source: Arc::new(source),
29        }
30    }
31
32    /// Creates a reporter error from a stable message.
33    pub fn message(message: &str) -> Self {
34        Self::new(MessageError(message.into()))
35    }
36
37    /// Returns the original reporter error.
38    #[must_use]
39    pub fn source_error(&self) -> &(dyn Error + Send + Sync + 'static) {
40        self.source.as_ref()
41    }
42}
43
44impl fmt::Display for ReporterError {
45    /// Formats the original reporter error.
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        self.source.fmt(formatter)
48    }
49}
50
51impl Error for ReporterError {
52    /// Returns the original reporter error as the source.
53    fn source(&self) -> Option<&(dyn Error + 'static)> {
54        Some(self.source.as_ref())
55    }
56}
57
58/// Message-backed error used by [`ReporterError::message`].
59#[derive(Debug)]
60struct MessageError(String);
61
62impl fmt::Display for MessageError {
63    /// Formats the stored message.
64    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
65        formatter.write_str(&self.0)
66    }
67}
68
69impl Error for MessageError {}