Skip to main content

unityrs_core/provider/
exception.rs

1//! External generator exceptions, including caller-defined Python subclasses.
2use std::sync::Arc;
3
4/// A generator exception preserved for a dynamic-language boundary.
5/// Classification is supplied separately from its name: custom subclasses of
6/// `ValueError` follow the same fallback as `ValueError` itself.
7#[derive(Clone, Debug, PartialEq, Eq)]
8#[non_exhaustive]
9pub struct PythonException {
10    // Share the payload so provider and reader errors stay small, and clones
11    // preserve both the exception and its ancestry without allocating.
12    data: Arc<ExceptionData>,
13}
14
15#[derive(Debug, PartialEq, Eq)]
16struct ExceptionData {
17    type_name: Arc<str>,
18    message: Arc<str>,
19    is_value_error: bool,
20}
21
22const _: () = crate::send_sync::<PythonException>();
23
24impl PythonException {
25    /// Preserve a Python failure and its independently determined ancestry.
26    #[must_use]
27    pub fn new(type_name: Arc<str>, message: Arc<str>, is_value_error: bool) -> Self {
28        Self {
29            data: Arc::new(ExceptionData {
30                type_name,
31                message,
32                is_value_error,
33            }),
34        }
35    }
36
37    /// Python's exception type name.
38    #[must_use]
39    pub fn as_str(&self) -> &str {
40        &self.data.type_name
41    }
42
43    /// Python's `str(exception)`, without the provider's diagnostic prefix.
44    #[must_use]
45    pub fn message(&self) -> &str {
46        &self.data.message
47    }
48
49    /// Whether `isinstance(exception, ValueError)` holds in Python.
50    #[must_use]
51    pub fn is_value_error(&self) -> bool {
52        self.data.is_value_error
53    }
54}