Skip to main content

pyo3/err/
mod.rs

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