pyo3/err/
mod.rs

1use crate::ffi_ptr_ext::FfiPtrExt;
2use crate::instance::Bound;
3#[cfg(Py_3_11)]
4use crate::intern;
5use crate::panic::PanicException;
6use crate::py_result_ext::PyResultExt;
7use crate::type_object::PyTypeInfo;
8use crate::types::any::PyAnyMethods;
9#[cfg(Py_3_11)]
10use crate::types::PyString;
11use crate::types::{
12    string::PyStringMethods, traceback::PyTracebackMethods, typeobject::PyTypeMethods, PyTraceback,
13    PyType,
14};
15use crate::{exceptions::PyBaseException, ffi};
16use crate::{BoundObject, Py, PyAny, Python};
17use std::ffi::CStr;
18
19mod cast_error;
20mod downcast_error;
21mod err_state;
22mod impls;
23
24use crate::conversion::IntoPyObject;
25use err_state::{PyErrState, PyErrStateLazyFnOutput, PyErrStateNormalized};
26use std::convert::Infallible;
27use std::ptr;
28
29pub use cast_error::{CastError, CastIntoError};
30#[allow(deprecated)]
31pub use downcast_error::{DowncastError, DowncastIntoError};
32
33/// Represents a Python exception.
34///
35/// To avoid needing access to [`Python`] in `Into` conversions to create `PyErr` (thus improving
36/// compatibility with `?` and other Rust errors) this type supports creating exceptions instances
37/// in a lazy fashion, where the full Python object for the exception is created only when needed.
38///
39/// Accessing the contained exception in any way, such as with [`value`](PyErr::value),
40/// [`get_type`](PyErr::get_type), or [`is_instance`](PyErr::is_instance)
41/// will create the full exception object if it was not already created.
42pub struct PyErr {
43    state: PyErrState,
44}
45
46// The inner value is only accessed through ways that require proving the gil is held
47#[cfg(feature = "nightly")]
48unsafe impl crate::marker::Ungil for PyErr {}
49
50/// Represents the result of a Python call.
51pub type PyResult<T> = Result<T, PyErr>;
52
53/// Helper conversion trait that allows to use custom arguments for lazy exception construction.
54pub trait PyErrArguments: Send + Sync {
55    /// Arguments for exception
56    fn arguments(self, py: Python<'_>) -> Py<PyAny>;
57}
58
59impl<T> PyErrArguments for T
60where
61    T: for<'py> IntoPyObject<'py> + Send + Sync,
62{
63    fn arguments(self, py: Python<'_>) -> Py<PyAny> {
64        // FIXME: `arguments` should become fallible
65        match self.into_pyobject(py) {
66            Ok(obj) => obj.into_any().unbind(),
67            Err(e) => panic!("Converting PyErr arguments failed: {}", e.into()),
68        }
69    }
70}
71
72impl PyErr {
73    /// Creates a new PyErr of type `T`.
74    ///
75    /// `args` can be:
76    /// * a tuple: the exception instance will be created using the equivalent to the Python
77    ///   expression `T(*tuple)`
78    /// * any other value: the exception instance will be created using the equivalent to the Python
79    ///   expression `T(value)`
80    ///
81    /// This exception instance will be initialized lazily. This avoids the need for the Python GIL
82    /// to be held, but requires `args` to be `Send` and `Sync`. If `args` is not `Send` or `Sync`,
83    /// consider using [`PyErr::from_value`] instead.
84    ///
85    /// If `T` does not inherit from `BaseException`, then a `TypeError` will be returned.
86    ///
87    /// If calling T's constructor with `args` raises an exception, that exception will be returned.
88    ///
89    /// # Examples
90    ///
91    /// ```
92    /// use pyo3::prelude::*;
93    /// use pyo3::exceptions::PyTypeError;
94    ///
95    /// #[pyfunction]
96    /// fn always_throws() -> PyResult<()> {
97    ///     Err(PyErr::new::<PyTypeError, _>("Error message"))
98    /// }
99    /// #
100    /// # Python::attach(|py| {
101    /// #     let fun = pyo3::wrap_pyfunction!(always_throws, py).unwrap();
102    /// #     let err = fun.call0().expect_err("called a function that should always return an error but the return value was Ok");
103    /// #     assert!(err.is_instance_of::<PyTypeError>(py))
104    /// # });
105    /// ```
106    ///
107    /// In most cases, you can use a concrete exception's constructor instead:
108    ///
109    /// ```
110    /// use pyo3::prelude::*;
111    /// use pyo3::exceptions::PyTypeError;
112    ///
113    /// #[pyfunction]
114    /// fn always_throws() -> PyResult<()> {
115    ///     Err(PyTypeError::new_err("Error message"))
116    /// }
117    /// #
118    /// # Python::attach(|py| {
119    /// #     let fun = pyo3::wrap_pyfunction!(always_throws, py).unwrap();
120    /// #     let err = fun.call0().expect_err("called a function that should always return an error but the return value was Ok");
121    /// #     assert!(err.is_instance_of::<PyTypeError>(py))
122    /// # });
123    /// ```
124    #[inline]
125    pub fn new<T, A>(args: A) -> PyErr
126    where
127        T: PyTypeInfo,
128        A: PyErrArguments + Send + Sync + 'static,
129    {
130        PyErr::from_state(PyErrState::lazy(Box::new(move |py| {
131            PyErrStateLazyFnOutput {
132                ptype: T::type_object(py).into(),
133                pvalue: args.arguments(py),
134            }
135        })))
136    }
137
138    /// Constructs a new PyErr from the given Python type and arguments.
139    ///
140    /// `ty` is the exception type; usually one of the standard exceptions
141    /// like `exceptions::PyRuntimeError`.
142    ///
143    /// `args` is either a tuple or a single value, with the same meaning as in [`PyErr::new`].
144    ///
145    /// If `ty` does not inherit from `BaseException`, then a `TypeError` will be returned.
146    ///
147    /// If calling `ty` with `args` raises an exception, that exception will be returned.
148    pub fn from_type<A>(ty: Bound<'_, PyType>, args: A) -> PyErr
149    where
150        A: PyErrArguments + Send + Sync + 'static,
151    {
152        PyErr::from_state(PyErrState::lazy_arguments(ty.unbind().into_any(), args))
153    }
154
155    /// Creates a new PyErr.
156    ///
157    /// If `obj` is a Python exception object, the PyErr will contain that object.
158    ///
159    /// If `obj` is a Python exception type object, this is equivalent to `PyErr::from_type(obj, ())`.
160    ///
161    /// Otherwise, a `TypeError` is created.
162    ///
163    /// # Examples
164    /// ```rust
165    /// use pyo3::prelude::*;
166    /// use pyo3::PyTypeInfo;
167    /// use pyo3::exceptions::PyTypeError;
168    /// use pyo3::types::PyString;
169    ///
170    /// Python::attach(|py| {
171    ///     // Case #1: Exception object
172    ///     let err = PyErr::from_value(PyTypeError::new_err("some type error")
173    ///         .value(py).clone().into_any());
174    ///     assert_eq!(err.to_string(), "TypeError: some type error");
175    ///
176    ///     // Case #2: Exception type
177    ///     let err = PyErr::from_value(PyTypeError::type_object(py).into_any());
178    ///     assert_eq!(err.to_string(), "TypeError: ");
179    ///
180    ///     // Case #3: Invalid exception value
181    ///     let err = PyErr::from_value(PyString::new(py, "foo").into_any());
182    ///     assert_eq!(
183    ///         err.to_string(),
184    ///         "TypeError: exceptions must derive from BaseException"
185    ///     );
186    /// });
187    /// ```
188    pub fn from_value(obj: Bound<'_, PyAny>) -> PyErr {
189        let state = match obj.cast_into::<PyBaseException>() {
190            Ok(obj) => PyErrState::normalized(PyErrStateNormalized::new(obj)),
191            Err(err) => {
192                // Assume obj is Type[Exception]; let later normalization handle if this
193                // is not the case
194                let obj = err.into_inner();
195                let py = obj.py();
196                PyErrState::lazy_arguments(obj.unbind(), py.None())
197            }
198        };
199
200        PyErr::from_state(state)
201    }
202
203    /// Returns the type of this exception.
204    ///
205    /// # Examples
206    /// ```rust
207    /// use pyo3::{prelude::*, exceptions::PyTypeError, types::PyType};
208    ///
209    /// Python::attach(|py| {
210    ///     let err: PyErr = PyTypeError::new_err(("some type error",));
211    ///     assert!(err.get_type(py).is(&PyType::new::<PyTypeError>(py)));
212    /// });
213    /// ```
214    pub fn get_type<'py>(&self, py: Python<'py>) -> Bound<'py, PyType> {
215        self.normalized(py).ptype(py)
216    }
217
218    /// Returns the value of this exception.
219    ///
220    /// # Examples
221    ///
222    /// ```rust
223    /// use pyo3::{exceptions::PyTypeError, PyErr, Python};
224    ///
225    /// Python::attach(|py| {
226    ///     let err: PyErr = PyTypeError::new_err(("some type error",));
227    ///     assert!(err.is_instance_of::<PyTypeError>(py));
228    ///     assert_eq!(err.value(py).to_string(), "some type error");
229    /// });
230    /// ```
231    pub fn value<'py>(&self, py: Python<'py>) -> &Bound<'py, PyBaseException> {
232        self.normalized(py).pvalue.bind(py)
233    }
234
235    /// Consumes self to take ownership of the exception value contained in this error.
236    pub fn into_value(self, py: Python<'_>) -> Py<PyBaseException> {
237        // NB technically this causes one reference count increase and decrease in quick succession
238        // on pvalue, but it's probably not worth optimizing this right now for the additional code
239        // complexity.
240        let normalized = self.normalized(py);
241        let exc = normalized.pvalue.clone_ref(py);
242        if let Some(tb) = normalized.ptraceback(py) {
243            unsafe {
244                ffi::PyException_SetTraceback(exc.as_ptr(), tb.as_ptr());
245            }
246        }
247        exc
248    }
249
250    /// Returns the traceback of this exception object.
251    ///
252    /// # Examples
253    /// ```rust
254    /// use pyo3::{exceptions::PyTypeError, Python};
255    ///
256    /// Python::attach(|py| {
257    ///     let err = PyTypeError::new_err(("some type error",));
258    ///     assert!(err.traceback(py).is_none());
259    /// });
260    /// ```
261    pub fn traceback<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyTraceback>> {
262        self.normalized(py).ptraceback(py)
263    }
264
265    /// Gets whether an error is present in the Python interpreter's global state.
266    #[inline]
267    pub fn occurred(_: Python<'_>) -> bool {
268        unsafe { !ffi::PyErr_Occurred().is_null() }
269    }
270
271    /// Takes the current error from the Python interpreter's global state and clears the global
272    /// state. If no error is set, returns `None`.
273    ///
274    /// If the error is a `PanicException` (which would have originated from a panic in a pyo3
275    /// callback) then this function will resume the panic.
276    ///
277    /// Use this function when it is not known if an error should be present. If the error is
278    /// expected to have been set, for example from [`PyErr::occurred`] or by an error return value
279    /// from a C FFI function, use [`PyErr::fetch`].
280    pub fn take(py: Python<'_>) -> Option<PyErr> {
281        let state = PyErrStateNormalized::take(py)?;
282        let pvalue = state.pvalue.bind(py);
283        if ptr::eq(
284            pvalue.get_type().as_ptr(),
285            PanicException::type_object_raw(py).cast(),
286        ) {
287            let msg: String = pvalue
288                .str()
289                .map(|py_str| py_str.to_string_lossy().into())
290                .unwrap_or_else(|_| String::from("Unwrapped panic from Python code"));
291            Self::print_panic_and_unwind(py, PyErrState::normalized(state), msg)
292        }
293
294        Some(PyErr::from_state(PyErrState::normalized(state)))
295    }
296
297    fn print_panic_and_unwind(py: Python<'_>, state: PyErrState, msg: String) -> ! {
298        eprintln!("--- PyO3 is resuming a panic after fetching a PanicException from Python. ---");
299        eprintln!("Python stack trace below:");
300
301        state.restore(py);
302
303        unsafe {
304            ffi::PyErr_PrintEx(0);
305        }
306
307        std::panic::resume_unwind(Box::new(msg))
308    }
309
310    /// Equivalent to [PyErr::take], but when no error is set:
311    ///  - Panics in debug mode.
312    ///  - Returns a `SystemError` in release mode.
313    ///
314    /// This behavior is consistent with Python's internal handling of what happens when a C return
315    /// value indicates an error occurred but the global error state is empty. (A lack of exception
316    /// should be treated as a bug in the code which returned an error code but did not set an
317    /// exception.)
318    ///
319    /// Use this function when the error is expected to have been set, for example from
320    /// [PyErr::occurred] or by an error return value from a C FFI function.
321    #[cfg_attr(debug_assertions, track_caller)]
322    #[inline]
323    pub fn fetch(py: Python<'_>) -> PyErr {
324        const FAILED_TO_FETCH: &str = "attempted to fetch exception but none was set";
325        match PyErr::take(py) {
326            Some(err) => err,
327            #[cfg(debug_assertions)]
328            None => panic!("{}", FAILED_TO_FETCH),
329            #[cfg(not(debug_assertions))]
330            None => crate::exceptions::PySystemError::new_err(FAILED_TO_FETCH),
331        }
332    }
333
334    /// Creates a new exception type with the given name and docstring.
335    ///
336    /// - `base` can be an existing exception type to subclass, or a tuple of classes.
337    /// - `dict` specifies an optional dictionary of class variables and methods.
338    /// - `doc` will be the docstring seen by python users.
339    ///
340    ///
341    /// # Errors
342    ///
343    /// This function returns an error if `name` is not of the form `<module>.<ExceptionName>`.
344    pub fn new_type<'py>(
345        py: Python<'py>,
346        name: &CStr,
347        doc: Option<&CStr>,
348        base: Option<&Bound<'py, PyType>>,
349        dict: Option<Py<PyAny>>,
350    ) -> PyResult<Py<PyType>> {
351        let base: *mut ffi::PyObject = match base {
352            None => std::ptr::null_mut(),
353            Some(obj) => obj.as_ptr(),
354        };
355
356        let dict: *mut ffi::PyObject = match dict {
357            None => std::ptr::null_mut(),
358            Some(obj) => obj.as_ptr(),
359        };
360
361        let doc_ptr = match doc.as_ref() {
362            Some(c) => c.as_ptr(),
363            None => std::ptr::null(),
364        };
365
366        // SAFETY: correct call to FFI function, return value is known to be a new
367        // exception type or null on error
368        unsafe {
369            ffi::PyErr_NewExceptionWithDoc(name.as_ptr(), doc_ptr, base, dict)
370                .assume_owned_or_err(py)
371                .cast_into_unchecked()
372        }
373        .map(Bound::unbind)
374    }
375
376    /// Prints a standard traceback to `sys.stderr`.
377    pub fn display(&self, py: Python<'_>) {
378        #[cfg(Py_3_12)]
379        unsafe {
380            ffi::PyErr_DisplayException(self.value(py).as_ptr())
381        }
382
383        #[cfg(not(Py_3_12))]
384        unsafe {
385            // keep the bound `traceback` alive for entire duration of
386            // PyErr_Display. if we inline this, the `Bound` will be dropped
387            // after the argument got evaluated, leading to call with a dangling
388            // pointer.
389            let traceback = self.traceback(py);
390            let type_bound = self.get_type(py);
391            ffi::PyErr_Display(
392                type_bound.as_ptr(),
393                self.value(py).as_ptr(),
394                traceback
395                    .as_ref()
396                    .map_or(std::ptr::null_mut(), |traceback| traceback.as_ptr()),
397            )
398        }
399    }
400
401    /// Calls `sys.excepthook` and then prints a standard traceback to `sys.stderr`.
402    pub fn print(&self, py: Python<'_>) {
403        self.clone_ref(py).restore(py);
404        unsafe { ffi::PyErr_PrintEx(0) }
405    }
406
407    /// Calls `sys.excepthook` and then prints a standard traceback to `sys.stderr`.
408    ///
409    /// Additionally sets `sys.last_{type,value,traceback,exc}` attributes to this exception.
410    pub fn print_and_set_sys_last_vars(&self, py: Python<'_>) {
411        self.clone_ref(py).restore(py);
412        unsafe { ffi::PyErr_PrintEx(1) }
413    }
414
415    /// Returns true if the current exception matches the exception in `exc`.
416    ///
417    /// If `exc` is a class object, this also returns `true` when `self` is an instance of a subclass.
418    /// If `exc` is a tuple, all exceptions in the tuple (and recursively in subtuples) are searched for a match.
419    pub fn matches<'py, T>(&self, py: Python<'py>, exc: T) -> Result<bool, T::Error>
420    where
421        T: IntoPyObject<'py>,
422    {
423        Ok(self.is_instance(py, &exc.into_pyobject(py)?.into_any().as_borrowed()))
424    }
425
426    /// Returns true if the current exception is instance of `T`.
427    #[inline]
428    pub fn is_instance(&self, py: Python<'_>, ty: &Bound<'_, PyAny>) -> bool {
429        let type_bound = self.get_type(py);
430        (unsafe { ffi::PyErr_GivenExceptionMatches(type_bound.as_ptr(), ty.as_ptr()) }) != 0
431    }
432
433    /// Returns true if the current exception is instance of `T`.
434    #[inline]
435    pub fn is_instance_of<T>(&self, py: Python<'_>) -> bool
436    where
437        T: PyTypeInfo,
438    {
439        self.is_instance(py, &T::type_object(py))
440    }
441
442    /// Writes the error back to the Python interpreter's global state.
443    /// This is the opposite of `PyErr::fetch()`.
444    #[inline]
445    pub fn restore(self, py: Python<'_>) {
446        self.state.restore(py)
447    }
448
449    /// Reports the error as unraisable.
450    ///
451    /// This calls `sys.unraisablehook()` using the current exception and obj argument.
452    ///
453    /// This method is useful to report errors in situations where there is no good mechanism
454    /// to report back to the Python land.  In Python this is used to indicate errors in
455    /// background threads or destructors which are protected.  In Rust code this is commonly
456    /// useful when you are calling into a Python callback which might fail, but there is no
457    /// obvious way to handle this error other than logging it.
458    ///
459    /// Calling this method has the benefit that the error goes back into a standardized callback
460    /// in Python which for instance allows unittests to ensure that no unraisable error
461    /// actually happened by hooking `sys.unraisablehook`.
462    ///
463    /// Example:
464    /// ```rust
465    /// # use pyo3::prelude::*;
466    /// # use pyo3::exceptions::PyRuntimeError;
467    /// # fn failing_function() -> PyResult<()> { Err(PyRuntimeError::new_err("foo")) }
468    /// # fn main() -> PyResult<()> {
469    /// Python::attach(|py| {
470    ///     match failing_function() {
471    ///         Err(pyerr) => pyerr.write_unraisable(py, None),
472    ///         Ok(..) => { /* do something here */ }
473    ///     }
474    ///     Ok(())
475    /// })
476    /// # }
477    #[inline]
478    pub fn write_unraisable(self, py: Python<'_>, obj: Option<&Bound<'_, PyAny>>) {
479        self.restore(py);
480        unsafe { ffi::PyErr_WriteUnraisable(obj.map_or(std::ptr::null_mut(), Bound::as_ptr)) }
481    }
482
483    /// Issues a warning message.
484    ///
485    /// May return an `Err(PyErr)` if warnings-as-errors is enabled.
486    ///
487    /// Equivalent to `warnings.warn()` in Python.
488    ///
489    /// The `category` should be one of the `Warning` classes available in
490    /// [`pyo3::exceptions`](crate::exceptions), or a subclass.  The Python
491    /// object can be retrieved using [`Python::get_type()`].
492    ///
493    /// Example:
494    /// ```rust
495    /// # use pyo3::prelude::*;
496    /// # use pyo3::ffi::c_str;
497    /// # fn main() -> PyResult<()> {
498    /// Python::attach(|py| {
499    ///     let user_warning = py.get_type::<pyo3::exceptions::PyUserWarning>();
500    ///     PyErr::warn(py, &user_warning, c"I am warning you", 0)?;
501    ///     Ok(())
502    /// })
503    /// # }
504    /// ```
505    pub fn warn<'py>(
506        py: Python<'py>,
507        category: &Bound<'py, PyAny>,
508        message: &CStr,
509        stacklevel: i32,
510    ) -> PyResult<()> {
511        error_on_minusone(py, unsafe {
512            ffi::PyErr_WarnEx(
513                category.as_ptr(),
514                message.as_ptr(),
515                stacklevel as ffi::Py_ssize_t,
516            )
517        })
518    }
519
520    /// Issues a warning message, with more control over the warning attributes.
521    ///
522    /// May return a `PyErr` if warnings-as-errors is enabled.
523    ///
524    /// Equivalent to `warnings.warn_explicit()` in Python.
525    ///
526    /// The `category` should be one of the `Warning` classes available in
527    /// [`pyo3::exceptions`](crate::exceptions), or a subclass.
528    pub fn warn_explicit<'py>(
529        py: Python<'py>,
530        category: &Bound<'py, PyAny>,
531        message: &CStr,
532        filename: &CStr,
533        lineno: i32,
534        module: Option<&CStr>,
535        registry: Option<&Bound<'py, PyAny>>,
536    ) -> PyResult<()> {
537        let module_ptr = match module {
538            None => std::ptr::null_mut(),
539            Some(s) => s.as_ptr(),
540        };
541        let registry: *mut ffi::PyObject = match registry {
542            None => std::ptr::null_mut(),
543            Some(obj) => obj.as_ptr(),
544        };
545        error_on_minusone(py, unsafe {
546            ffi::PyErr_WarnExplicit(
547                category.as_ptr(),
548                message.as_ptr(),
549                filename.as_ptr(),
550                lineno,
551                module_ptr,
552                registry,
553            )
554        })
555    }
556
557    /// Clone the PyErr. This requires the GIL, which is why PyErr does not implement Clone.
558    ///
559    /// # Examples
560    /// ```rust
561    /// use pyo3::{exceptions::PyTypeError, PyErr, Python, prelude::PyAnyMethods};
562    /// Python::attach(|py| {
563    ///     let err: PyErr = PyTypeError::new_err(("some type error",));
564    ///     let err_clone = err.clone_ref(py);
565    ///     assert!(err.get_type(py).is(&err_clone.get_type(py)));
566    ///     assert!(err.value(py).is(err_clone.value(py)));
567    ///     match err.traceback(py) {
568    ///         None => assert!(err_clone.traceback(py).is_none()),
569    ///         Some(tb) => assert!(err_clone.traceback(py).unwrap().is(&tb)),
570    ///     }
571    /// });
572    /// ```
573    #[inline]
574    pub fn clone_ref(&self, py: Python<'_>) -> PyErr {
575        PyErr::from_state(PyErrState::normalized(self.normalized(py).clone_ref(py)))
576    }
577
578    /// Return the cause (either an exception instance, or None, set by `raise ... from ...`)
579    /// associated with the exception, as accessible from Python through `__cause__`.
580    pub fn cause(&self, py: Python<'_>) -> Option<PyErr> {
581        use crate::ffi_ptr_ext::FfiPtrExt;
582        let obj =
583            unsafe { ffi::PyException_GetCause(self.value(py).as_ptr()).assume_owned_or_opt(py) };
584        // PyException_GetCause is documented as potentially returning PyNone, but only GraalPy seems to actually do that
585        #[cfg(GraalPy)]
586        if let Some(cause) = &obj {
587            if cause.is_none() {
588                return None;
589            }
590        }
591        obj.map(Self::from_value)
592    }
593
594    /// Set the cause associated with the exception, pass `None` to clear it.
595    pub fn set_cause(&self, py: Python<'_>, cause: Option<Self>) {
596        let value = self.value(py);
597        let cause = cause.map(|err| err.into_value(py));
598        unsafe {
599            // PyException_SetCause _steals_ a reference to cause, so must use .into_ptr()
600            ffi::PyException_SetCause(
601                value.as_ptr(),
602                cause.map_or(std::ptr::null_mut(), Py::into_ptr),
603            );
604        }
605    }
606
607    /// Equivalent to calling `add_note` on the exception in Python.
608    #[cfg(Py_3_11)]
609    pub fn add_note<N: for<'py> IntoPyObject<'py, Target = PyString>>(
610        &self,
611        py: Python<'_>,
612        note: N,
613    ) -> PyResult<()> {
614        self.value(py)
615            .call_method1(intern!(py, "add_note"), (note,))?;
616        Ok(())
617    }
618
619    #[inline]
620    fn from_state(state: PyErrState) -> PyErr {
621        PyErr { state }
622    }
623
624    #[inline]
625    fn normalized(&self, py: Python<'_>) -> &PyErrStateNormalized {
626        self.state.as_normalized(py)
627    }
628}
629
630impl std::fmt::Debug for PyErr {
631    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
632        Python::attach(|py| {
633            f.debug_struct("PyErr")
634                .field("type", &self.get_type(py))
635                .field("value", self.value(py))
636                .field(
637                    "traceback",
638                    &self.traceback(py).map(|tb| match tb.format() {
639                        Ok(s) => s,
640                        Err(err) => {
641                            err.write_unraisable(py, Some(&tb));
642                            // It would be nice to format what we can of the
643                            // error, but we can't guarantee that the error
644                            // won't have another unformattable traceback inside
645                            // it and we want to avoid an infinite recursion.
646                            format!("<unformattable {tb:?}>")
647                        }
648                    }),
649                )
650                .finish()
651        })
652    }
653}
654
655impl std::fmt::Display for PyErr {
656    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
657        Python::attach(|py| {
658            let value = self.value(py);
659            let type_name = value.get_type().qualname().map_err(|_| std::fmt::Error)?;
660            write!(f, "{type_name}")?;
661            if let Ok(s) = value.str() {
662                write!(f, ": {}", &s.to_string_lossy())
663            } else {
664                write!(f, ": <exception str() failed>")
665            }
666        })
667    }
668}
669
670impl std::error::Error for PyErr {}
671
672impl<'py> IntoPyObject<'py> for PyErr {
673    type Target = PyBaseException;
674    type Output = Bound<'py, Self::Target>;
675    type Error = Infallible;
676
677    #[inline]
678    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
679        Ok(self.into_value(py).into_bound(py))
680    }
681}
682
683impl<'py> IntoPyObject<'py> for &PyErr {
684    type Target = PyBaseException;
685    type Output = Bound<'py, Self::Target>;
686    type Error = Infallible;
687
688    #[inline]
689    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
690        self.clone_ref(py).into_pyobject(py)
691    }
692}
693
694/// Python exceptions that can be converted to [`PyErr`].
695///
696/// This is used to implement [`From<Bound<'_, T>> for PyErr`].
697///
698/// Users should not need to implement this trait directly. It is implemented automatically in the
699/// [`crate::import_exception!`] and [`crate::create_exception!`] macros.
700pub trait ToPyErr {}
701
702impl<'py, T> std::convert::From<Bound<'py, T>> for PyErr
703where
704    T: ToPyErr,
705{
706    #[inline]
707    fn from(err: Bound<'py, T>) -> PyErr {
708        PyErr::from_value(err.into_any())
709    }
710}
711
712/// Returns Ok if the error code is not -1.
713#[inline]
714pub(crate) fn error_on_minusone<T: SignedInteger>(py: Python<'_>, result: T) -> PyResult<()> {
715    if result != T::MINUS_ONE {
716        Ok(())
717    } else {
718        Err(PyErr::fetch(py))
719    }
720}
721
722pub(crate) trait SignedInteger: Eq {
723    const MINUS_ONE: Self;
724}
725
726macro_rules! impl_signed_integer {
727    ($t:ty) => {
728        impl SignedInteger for $t {
729            const MINUS_ONE: Self = -1;
730        }
731    };
732}
733
734impl_signed_integer!(i8);
735impl_signed_integer!(i16);
736impl_signed_integer!(i32);
737impl_signed_integer!(i64);
738impl_signed_integer!(i128);
739impl_signed_integer!(isize);
740
741#[cfg(test)]
742mod tests {
743    use super::PyErrState;
744    use crate::exceptions::{self, PyTypeError, PyValueError};
745    use crate::impl_::pyclass::{value_of, IsSend, IsSync};
746    use crate::test_utils::assert_warnings;
747    use crate::{PyErr, PyTypeInfo, Python};
748
749    #[test]
750    fn no_error() {
751        assert!(Python::attach(PyErr::take).is_none());
752    }
753
754    #[test]
755    fn set_valueerror() {
756        Python::attach(|py| {
757            let err: PyErr = exceptions::PyValueError::new_err("some exception message");
758            assert!(err.is_instance_of::<exceptions::PyValueError>(py));
759            err.restore(py);
760            assert!(PyErr::occurred(py));
761            let err = PyErr::fetch(py);
762            assert!(err.is_instance_of::<exceptions::PyValueError>(py));
763            assert_eq!(err.to_string(), "ValueError: some exception message");
764        })
765    }
766
767    #[test]
768    fn invalid_error_type() {
769        Python::attach(|py| {
770            let err: PyErr = PyErr::new::<crate::types::PyString, _>(());
771            assert!(err.is_instance_of::<exceptions::PyTypeError>(py));
772            err.restore(py);
773            let err = PyErr::fetch(py);
774
775            assert!(err.is_instance_of::<exceptions::PyTypeError>(py));
776            assert_eq!(
777                err.to_string(),
778                "TypeError: exceptions must derive from BaseException"
779            );
780        })
781    }
782
783    #[test]
784    fn set_typeerror() {
785        Python::attach(|py| {
786            let err: PyErr = exceptions::PyTypeError::new_err(());
787            err.restore(py);
788            assert!(PyErr::occurred(py));
789            drop(PyErr::fetch(py));
790        });
791    }
792
793    #[test]
794    #[should_panic(expected = "new panic")]
795    fn fetching_panic_exception_resumes_unwind() {
796        use crate::panic::PanicException;
797
798        Python::attach(|py| {
799            let err: PyErr = PanicException::new_err("new panic");
800            err.restore(py);
801            assert!(PyErr::occurred(py));
802
803            // should resume unwind
804            let _ = PyErr::fetch(py);
805        });
806    }
807
808    #[test]
809    #[should_panic(expected = "new panic")]
810    #[cfg(not(Py_3_12))]
811    fn fetching_normalized_panic_exception_resumes_unwind() {
812        use crate::panic::PanicException;
813
814        Python::attach(|py| {
815            let err: PyErr = PanicException::new_err("new panic");
816            // Restoring an error doesn't normalize it before Python 3.12,
817            // so we have to explicitly test this case.
818            let _ = err.normalized(py);
819            err.restore(py);
820            assert!(PyErr::occurred(py));
821
822            // should resume unwind
823            let _ = PyErr::fetch(py);
824        });
825    }
826
827    #[test]
828    fn err_debug() {
829        // Debug representation should be like the following (without the newlines):
830        // PyErr {
831        //     type: <class 'Exception'>,
832        //     value: Exception('banana'),
833        //     traceback:  Some(\"Traceback (most recent call last):\\n  File \\\"<string>\\\", line 1, in <module>\\n\")
834        // }
835
836        Python::attach(|py| {
837            let err = py
838                .run(c"raise Exception('banana')", None, None)
839                .expect_err("raising should have given us an error");
840
841            let debug_str = format!("{err:?}");
842            assert!(debug_str.starts_with("PyErr { "));
843            assert!(debug_str.ends_with(" }"));
844
845            // Strip "PyErr { " and " }". Split into 3 substrings to separate type,
846            // value, and traceback while not splitting the string within traceback.
847            let mut fields = debug_str["PyErr { ".len()..debug_str.len() - 2].splitn(3, ", ");
848
849            assert_eq!(fields.next().unwrap(), "type: <class 'Exception'>");
850            assert_eq!(fields.next().unwrap(), "value: Exception('banana')");
851            assert_eq!(
852                fields.next().unwrap(),
853                "traceback: Some(\"Traceback (most recent call last):\\n  File \\\"<string>\\\", line 1, in <module>\\n\")"
854            );
855
856            assert!(fields.next().is_none());
857        });
858    }
859
860    #[test]
861    fn err_display() {
862        Python::attach(|py| {
863            let err = py
864                .run(c"raise Exception('banana')", None, None)
865                .expect_err("raising should have given us an error");
866            assert_eq!(err.to_string(), "Exception: banana");
867        });
868    }
869
870    #[test]
871    fn test_pyerr_send_sync() {
872        assert!(value_of!(IsSend, PyErr));
873        assert!(value_of!(IsSync, PyErr));
874
875        assert!(value_of!(IsSend, PyErrState));
876        assert!(value_of!(IsSync, PyErrState));
877    }
878
879    #[test]
880    fn test_pyerr_matches() {
881        Python::attach(|py| {
882            let err = PyErr::new::<PyValueError, _>("foo");
883            assert!(err.matches(py, PyValueError::type_object(py)).unwrap());
884
885            assert!(err
886                .matches(
887                    py,
888                    (PyValueError::type_object(py), PyTypeError::type_object(py))
889                )
890                .unwrap());
891
892            assert!(!err.matches(py, PyTypeError::type_object(py)).unwrap());
893
894            // String is not a valid exception class, so we should get a TypeError
895            let err: PyErr = PyErr::from_type(crate::types::PyString::type_object(py), "foo");
896            assert!(err.matches(py, PyTypeError::type_object(py)).unwrap());
897        })
898    }
899
900    #[test]
901    fn test_pyerr_cause() {
902        Python::attach(|py| {
903            let err = py
904                .run(c"raise Exception('banana')", None, None)
905                .expect_err("raising should have given us an error");
906            assert!(err.cause(py).is_none());
907
908            let err = py
909                .run(
910                    c"raise Exception('banana') from Exception('apple')",
911                    None,
912                    None,
913                )
914                .expect_err("raising should have given us an error");
915            let cause = err
916                .cause(py)
917                .expect("raising from should have given us a cause");
918            assert_eq!(cause.to_string(), "Exception: apple");
919
920            err.set_cause(py, None);
921            assert!(err.cause(py).is_none());
922
923            let new_cause = exceptions::PyValueError::new_err("orange");
924            err.set_cause(py, Some(new_cause));
925            let cause = err
926                .cause(py)
927                .expect("set_cause should have given us a cause");
928            assert_eq!(cause.to_string(), "ValueError: orange");
929        });
930    }
931
932    #[test]
933    fn warnings() {
934        use crate::types::any::PyAnyMethods;
935        // Note: although the warning filter is interpreter global, keeping the
936        // GIL locked should prevent effects to be visible to other testing
937        // threads.
938        Python::attach(|py| {
939            let cls = py.get_type::<exceptions::PyUserWarning>();
940
941            // Reset warning filter to default state
942            let warnings = py.import("warnings").unwrap();
943            warnings.call_method0("resetwarnings").unwrap();
944
945            // First, test the warning is emitted
946            assert_warnings!(
947                py,
948                { PyErr::warn(py, &cls, c"I am warning you", 0).unwrap() },
949                [(exceptions::PyUserWarning, "I am warning you")]
950            );
951
952            // Test with raising
953            warnings
954                .call_method1("simplefilter", ("error", &cls))
955                .unwrap();
956            PyErr::warn(py, &cls, c"I am warning you", 0).unwrap_err();
957
958            // Test with error for an explicit module
959            warnings.call_method0("resetwarnings").unwrap();
960            warnings
961                .call_method1("filterwarnings", ("error", "", &cls, "pyo3test"))
962                .unwrap();
963
964            // This has the wrong module and will not raise, just be emitted
965            assert_warnings!(
966                py,
967                { PyErr::warn(py, &cls, c"I am warning you", 0).unwrap() },
968                [(exceptions::PyUserWarning, "I am warning you")]
969            );
970
971            let err = PyErr::warn_explicit(
972                py,
973                &cls,
974                c"I am warning you",
975                c"pyo3test.py",
976                427,
977                None,
978                None,
979            )
980            .unwrap_err();
981            assert!(err
982                .value(py)
983                .getattr("args")
984                .unwrap()
985                .get_item(0)
986                .unwrap()
987                .eq("I am warning you")
988                .unwrap());
989
990            // Finally, reset filter again
991            warnings.call_method0("resetwarnings").unwrap();
992        });
993    }
994
995    #[test]
996    #[cfg(Py_3_11)]
997    fn test_add_note() {
998        use crate::types::any::PyAnyMethods;
999        Python::attach(|py| {
1000            let err = PyErr::new::<exceptions::PyValueError, _>("original error");
1001            err.add_note(py, "additional context").unwrap();
1002
1003            let notes = err.value(py).getattr("__notes__").unwrap();
1004            assert_eq!(notes.len().unwrap(), 1);
1005            assert_eq!(
1006                notes.get_item(0).unwrap().extract::<String>().unwrap(),
1007                "additional context"
1008            );
1009        });
1010    }
1011}