Skip to main content

qubit_executor/task/
task_execution_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 ******************************************************************************/
10use std::{
11    error::Error,
12    fmt,
13};
14
15/// Result type used by managed task handles.
16pub type TaskResult<R, E> = Result<R, TaskExecutionError<E>>;
17
18/// Error observed when retrieving the result of an accepted task.
19///
20/// This error is distinct from [`RejectedExecution`](crate::service::RejectedExecution).
21/// Rejection happens before a service accepts a task; `TaskExecutionError`
22/// describes what happened after the task was accepted.
23///
24/// # Type Parameters
25///
26/// * `E` - The error type returned by the task itself.
27///
28#[derive(Debug)]
29pub enum TaskExecutionError<E> {
30    /// The task ran and returned `Err(E)`.
31    Failed(E),
32
33    /// The task panicked while running.
34    Panicked,
35
36    /// The task was cancelled before producing a result.
37    Cancelled,
38}
39
40impl<E> TaskExecutionError<E> {
41    /// Returns true when this error wraps the task's own error value.
42    ///
43    /// # Returns
44    ///
45    /// `true` if the task returned `Err(E)`.
46    #[inline]
47    pub const fn is_failed(&self) -> bool {
48        matches!(self, Self::Failed(_))
49    }
50
51    /// Returns true when the task panicked.
52    ///
53    /// # Returns
54    ///
55    /// `true` if the task panicked while running.
56    #[inline]
57    pub const fn is_panicked(&self) -> bool {
58        matches!(self, Self::Panicked)
59    }
60
61    /// Returns true when the task was cancelled.
62    ///
63    /// # Returns
64    ///
65    /// `true` if the task was cancelled before producing a result.
66    #[inline]
67    pub const fn is_cancelled(&self) -> bool {
68        matches!(self, Self::Cancelled)
69    }
70}
71
72impl<E> fmt::Display for TaskExecutionError<E>
73where
74    E: fmt::Display,
75{
76    /// Formats this task execution error for users.
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        match self {
79            Self::Failed(err) => write!(f, "task failed: {err}"),
80            Self::Panicked => f.write_str("task panicked"),
81            Self::Cancelled => f.write_str("task was cancelled"),
82        }
83    }
84}
85
86impl<E> Error for TaskExecutionError<E> where E: Error + 'static {}