pyo3/err/mod.rs
1use crate::conversion::IntoPyObject;
2use crate::ffi_ptr_ext::FfiPtrExt;
3#[cfg(feature = "experimental-inspect")]
4use crate::inspect::PyStaticExpr;
5use crate::instance::Bound;
6#[cfg(Py_3_11)]
7use crate::intern;
8use crate::panic::PanicException;
9use crate::py_result_ext::PyResultExt;
10use crate::type_object::PyTypeInfo;
11use crate::types::any::PyAnyMethods;
12#[cfg(Py_3_11)]
13use crate::types::PyString;
14use crate::types::{
15 string::PyStringMethods, traceback::PyTracebackMethods, typeobject::PyTypeMethods, PyTraceback,
16 PyType,
17};
18use crate::{exceptions::PyBaseException, ffi};
19use crate::{BoundObject, Py, PyAny, Python};
20use err_state::{PyErrState, PyErrStateLazyFnOutput, PyErrStateNormalized};
21use std::convert::Infallible;
22use std::ffi::CStr;
23
24mod cast_error;
25mod downcast_error;
26mod err_state;
27mod impls;
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
283 if PanicException::is_exact_type_of(state.pvalue.bind(py)) {
284 Self::print_panic_and_unwind(py, state)
285 }
286
287 Some(PyErr::from_state(PyErrState::normalized(state)))
288 }
289
290 #[cold]
291 fn print_panic_and_unwind(py: Python<'_>, state: PyErrStateNormalized) -> ! {
292 let msg: String = state
293 .pvalue
294 .bind(py)
295 .str()
296 .map(|py_str| py_str.to_string_lossy().into())
297 .unwrap_or_else(|_| String::from("Unwrapped panic from Python code"));
298
299 eprintln!("--- PyO3 is resuming a panic after fetching a PanicException from Python. ---");
300 eprintln!("Python stack trace below:");
301
302 PyErrState::normalized(state).restore(py);
303
304 // SAFETY: thread is attached and error was just set in the interpreter
305 unsafe {
306 ffi::PyErr_PrintEx(0);
307 }
308
309 std::panic::resume_unwind(Box::new(msg))
310 }
311
312 /// Equivalent to [PyErr::take], but when no error is set:
313 /// - Panics in debug mode.
314 /// - Returns a `SystemError` in release mode.
315 ///
316 /// This behavior is consistent with Python's internal handling of what happens when a C return
317 /// value indicates an error occurred but the global error state is empty. (A lack of exception
318 /// should be treated as a bug in the code which returned an error code but did not set an
319 /// exception.)
320 ///
321 /// Use this function when the error is expected to have been set, for example from
322 /// [PyErr::occurred] or by an error return value from a C FFI function.
323 #[cfg_attr(debug_assertions, track_caller)]
324 #[inline]
325 pub fn fetch(py: Python<'_>) -> PyErr {
326 PyErr::take(py).unwrap_or_else(failed_to_fetch)
327 }
328
329 /// Creates a new exception type with the given name and docstring.
330 ///
331 /// - `base` can be an existing exception type to subclass, or a tuple of classes.
332 /// - `dict` specifies an optional dictionary of class variables and methods.
333 /// - `doc` will be the docstring seen by python users.
334 ///
335 ///
336 /// # Errors
337 ///
338 /// This function returns an error if `name` is not of the form `<module>.<ExceptionName>`.
339 pub fn new_type<'py>(
340 py: Python<'py>,
341 name: &CStr,
342 doc: Option<&CStr>,
343 base: Option<&Bound<'py, PyType>>,
344 dict: Option<Py<PyAny>>,
345 ) -> PyResult<Py<PyType>> {
346 let base: *mut ffi::PyObject = match base {
347 None => std::ptr::null_mut(),
348 Some(obj) => obj.as_ptr(),
349 };
350
351 let dict: *mut ffi::PyObject = match dict {
352 None => std::ptr::null_mut(),
353 Some(obj) => obj.as_ptr(),
354 };
355
356 let doc_ptr = match doc.as_ref() {
357 Some(c) => c.as_ptr(),
358 None => std::ptr::null(),
359 };
360
361 // SAFETY: correct call to FFI function, return value is known to be a new
362 // exception type or null on error
363 unsafe {
364 ffi::PyErr_NewExceptionWithDoc(name.as_ptr(), doc_ptr, base, dict)
365 .assume_owned_or_err(py)
366 .cast_into_unchecked()
367 }
368 .map(Bound::unbind)
369 }
370
371 /// Prints a standard traceback to `sys.stderr`.
372 pub fn display(&self, py: Python<'_>) {
373 #[cfg(Py_3_12)]
374 unsafe {
375 ffi::PyErr_DisplayException(self.value(py).as_ptr())
376 }
377
378 #[cfg(not(Py_3_12))]
379 unsafe {
380 // keep the bound `traceback` alive for entire duration of
381 // PyErr_Display. if we inline this, the `Bound` will be dropped
382 // after the argument got evaluated, leading to call with a dangling
383 // pointer.
384 let traceback = self.traceback(py);
385 let type_bound = self.get_type(py);
386 ffi::PyErr_Display(
387 type_bound.as_ptr(),
388 self.value(py).as_ptr(),
389 traceback
390 .as_ref()
391 .map_or(std::ptr::null_mut(), |traceback| traceback.as_ptr()),
392 )
393 }
394 }
395
396 /// Calls `sys.excepthook` and then prints a standard traceback to `sys.stderr`.
397 pub fn print(&self, py: Python<'_>) {
398 self.clone_ref(py).restore(py);
399 unsafe { ffi::PyErr_PrintEx(0) }
400 }
401
402 /// Calls `sys.excepthook` and then prints a standard traceback to `sys.stderr`.
403 ///
404 /// Additionally sets `sys.last_{type,value,traceback,exc}` attributes to this exception.
405 pub fn print_and_set_sys_last_vars(&self, py: Python<'_>) {
406 self.clone_ref(py).restore(py);
407 unsafe { ffi::PyErr_PrintEx(1) }
408 }
409
410 /// Returns true if the current exception matches the exception in `exc`.
411 ///
412 /// If `exc` is a class object, this also returns `true` when `self` is an instance of a subclass.
413 /// If `exc` is a tuple, all exceptions in the tuple (and recursively in subtuples) are searched for a match.
414 pub fn matches<'py, T>(&self, py: Python<'py>, exc: T) -> Result<bool, T::Error>
415 where
416 T: IntoPyObject<'py>,
417 {
418 Ok(self.is_instance(py, &exc.into_pyobject(py)?.into_any().as_borrowed()))
419 }
420
421 /// Returns true if the current exception is instance of `T`.
422 #[inline]
423 pub fn is_instance(&self, py: Python<'_>, ty: &Bound<'_, PyAny>) -> bool {
424 let type_bound = self.get_type(py);
425 (unsafe { ffi::PyErr_GivenExceptionMatches(type_bound.as_ptr(), ty.as_ptr()) }) != 0
426 }
427
428 /// Returns true if the current exception is instance of `T`.
429 #[inline]
430 pub fn is_instance_of<T>(&self, py: Python<'_>) -> bool
431 where
432 T: PyTypeInfo,
433 {
434 self.is_instance(py, &T::type_object(py))
435 }
436
437 /// Writes the error back to the Python interpreter's global state.
438 /// This is the opposite of `PyErr::fetch()`.
439 #[inline]
440 pub fn restore(self, py: Python<'_>) {
441 self.state.restore(py)
442 }
443
444 /// Reports the error as unraisable.
445 ///
446 /// This calls `sys.unraisablehook()` using the current exception and obj argument.
447 ///
448 /// This method is useful to report errors in situations where there is no good mechanism
449 /// to report back to the Python land. In Python this is used to indicate errors in
450 /// background threads or destructors which are protected. In Rust code this is commonly
451 /// useful when you are calling into a Python callback which might fail, but there is no
452 /// obvious way to handle this error other than logging it.
453 ///
454 /// Calling this method has the benefit that the error goes back into a standardized callback
455 /// in Python which for instance allows unittests to ensure that no unraisable error
456 /// actually happened by hooking `sys.unraisablehook`.
457 ///
458 /// Example:
459 /// ```rust
460 /// # use pyo3::prelude::*;
461 /// # use pyo3::exceptions::PyRuntimeError;
462 /// # fn failing_function() -> PyResult<()> { Err(PyRuntimeError::new_err("foo")) }
463 /// # fn main() -> PyResult<()> {
464 /// Python::attach(|py| {
465 /// match failing_function() {
466 /// Err(pyerr) => pyerr.write_unraisable(py, None),
467 /// Ok(..) => { /* do something here */ }
468 /// }
469 /// Ok(())
470 /// })
471 /// # }
472 #[inline]
473 pub fn write_unraisable(self, py: Python<'_>, obj: Option<&Bound<'_, PyAny>>) {
474 self.restore(py);
475 unsafe { ffi::PyErr_WriteUnraisable(obj.map_or(std::ptr::null_mut(), Bound::as_ptr)) }
476 }
477
478 /// Issues a warning message.
479 ///
480 /// May return an `Err(PyErr)` if warnings-as-errors is enabled.
481 ///
482 /// Equivalent to `warnings.warn()` in Python.
483 ///
484 /// The `category` should be one of the `Warning` classes available in
485 /// [`pyo3::exceptions`](crate::exceptions), or a subclass. The Python
486 /// object can be retrieved using [`Python::get_type()`].
487 ///
488 /// Example:
489 /// ```rust
490 /// # use pyo3::prelude::*;
491 /// # use pyo3::ffi::c_str;
492 /// # fn main() -> PyResult<()> {
493 /// Python::attach(|py| {
494 /// let user_warning = py.get_type::<pyo3::exceptions::PyUserWarning>();
495 /// PyErr::warn(py, &user_warning, c"I am warning you", 0)?;
496 /// Ok(())
497 /// })
498 /// # }
499 /// ```
500 pub fn warn<'py>(
501 py: Python<'py>,
502 category: &Bound<'py, PyAny>,
503 message: &CStr,
504 stacklevel: i32,
505 ) -> PyResult<()> {
506 error_on_minusone(py, unsafe {
507 ffi::PyErr_WarnEx(
508 category.as_ptr(),
509 message.as_ptr(),
510 stacklevel as ffi::Py_ssize_t,
511 )
512 })
513 }
514
515 /// Issues a warning message, with more control over the warning attributes.
516 ///
517 /// May return a `PyErr` if warnings-as-errors is enabled.
518 ///
519 /// Equivalent to `warnings.warn_explicit()` in Python.
520 ///
521 /// The `category` should be one of the `Warning` classes available in
522 /// [`pyo3::exceptions`](crate::exceptions), or a subclass.
523 pub fn warn_explicit<'py>(
524 py: Python<'py>,
525 category: &Bound<'py, PyAny>,
526 message: &CStr,
527 filename: &CStr,
528 lineno: i32,
529 module: Option<&CStr>,
530 registry: Option<&Bound<'py, PyAny>>,
531 ) -> PyResult<()> {
532 let module_ptr = match module {
533 None => std::ptr::null_mut(),
534 Some(s) => s.as_ptr(),
535 };
536 let registry: *mut ffi::PyObject = match registry {
537 None => std::ptr::null_mut(),
538 Some(obj) => obj.as_ptr(),
539 };
540 error_on_minusone(py, unsafe {
541 ffi::PyErr_WarnExplicit(
542 category.as_ptr(),
543 message.as_ptr(),
544 filename.as_ptr(),
545 lineno,
546 module_ptr,
547 registry,
548 )
549 })
550 }
551
552 /// Clone the PyErr. This requires the GIL, which is why PyErr does not implement Clone.
553 ///
554 /// # Examples
555 /// ```rust
556 /// use pyo3::{exceptions::PyTypeError, PyErr, Python, prelude::PyAnyMethods};
557 /// Python::attach(|py| {
558 /// let err: PyErr = PyTypeError::new_err(("some type error",));
559 /// let err_clone = err.clone_ref(py);
560 /// assert!(err.get_type(py).is(&err_clone.get_type(py)));
561 /// assert!(err.value(py).is(err_clone.value(py)));
562 /// match err.traceback(py) {
563 /// None => assert!(err_clone.traceback(py).is_none()),
564 /// Some(tb) => assert!(err_clone.traceback(py).unwrap().is(&tb)),
565 /// }
566 /// });
567 /// ```
568 #[inline]
569 pub fn clone_ref(&self, py: Python<'_>) -> PyErr {
570 PyErr::from_state(PyErrState::normalized(self.normalized(py).clone_ref(py)))
571 }
572
573 /// Return the cause (either an exception instance, or None, set by `raise ... from ...`)
574 /// associated with the exception, as accessible from Python through `__cause__`.
575 pub fn cause(&self, py: Python<'_>) -> Option<PyErr> {
576 use crate::ffi_ptr_ext::FfiPtrExt;
577 let obj =
578 unsafe { ffi::PyException_GetCause(self.value(py).as_ptr()).assume_owned_or_opt(py) };
579 // PyException_GetCause is documented as potentially returning PyNone, but only GraalPy seems to actually do that
580 #[cfg(GraalPy)]
581 if let Some(cause) = &obj {
582 if cause.is_none() {
583 return None;
584 }
585 }
586 obj.map(Self::from_value)
587 }
588
589 /// Set the cause associated with the exception, pass `None` to clear it.
590 pub fn set_cause(&self, py: Python<'_>, cause: Option<Self>) {
591 let value = self.value(py);
592 let cause = cause.map(|err| err.into_value(py));
593 unsafe {
594 // PyException_SetCause _steals_ a reference to cause, so must use .into_ptr()
595 ffi::PyException_SetCause(
596 value.as_ptr(),
597 cause.map_or(std::ptr::null_mut(), Py::into_ptr),
598 );
599 }
600 }
601
602 /// Equivalent to calling `add_note` on the exception in Python.
603 #[cfg(Py_3_11)]
604 pub fn add_note<N: for<'py> IntoPyObject<'py, Target = PyString>>(
605 &self,
606 py: Python<'_>,
607 note: N,
608 ) -> PyResult<()> {
609 self.value(py)
610 .call_method1(intern!(py, "add_note"), (note,))?;
611 Ok(())
612 }
613
614 #[inline]
615 fn from_state(state: PyErrState) -> PyErr {
616 PyErr { state }
617 }
618
619 #[inline]
620 fn normalized(&self, py: Python<'_>) -> &PyErrStateNormalized {
621 self.state.as_normalized(py)
622 }
623}
624
625/// Called when `PyErr::fetch` is called but no exception is set.
626#[cold]
627#[cfg_attr(debug_assertions, track_caller)]
628fn failed_to_fetch() -> PyErr {
629 const FAILED_TO_FETCH: &str = "attempted to fetch exception but none was set";
630
631 if cfg!(debug_assertions) {
632 panic!("{}", FAILED_TO_FETCH)
633 } else {
634 crate::exceptions::PySystemError::new_err(FAILED_TO_FETCH)
635 }
636}
637
638impl std::fmt::Debug for PyErr {
639 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
640 Python::attach(|py| {
641 f.debug_struct("PyErr")
642 .field("type", &self.get_type(py))
643 .field("value", self.value(py))
644 .field(
645 "traceback",
646 &self.traceback(py).map(|tb| match tb.format() {
647 Ok(s) => s,
648 Err(err) => {
649 err.write_unraisable(py, Some(&tb));
650 // It would be nice to format what we can of the
651 // error, but we can't guarantee that the error
652 // won't have another unformattable traceback inside
653 // it and we want to avoid an infinite recursion.
654 format!("<unformattable {tb:?}>")
655 }
656 }),
657 )
658 .finish()
659 })
660 }
661}
662
663impl std::fmt::Display for PyErr {
664 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
665 Python::attach(|py| {
666 let value = self.value(py);
667 let type_name = value.get_type().qualname().map_err(|_| std::fmt::Error)?;
668 write!(f, "{type_name}")?;
669 if let Ok(s) = value.str() {
670 write!(f, ": {}", &s.to_string_lossy())
671 } else {
672 write!(f, ": <exception str() failed>")
673 }
674 })
675 }
676}
677
678impl std::error::Error for PyErr {}
679
680impl<'py> IntoPyObject<'py> for PyErr {
681 type Target = PyBaseException;
682 type Output = Bound<'py, Self::Target>;
683 type Error = Infallible;
684
685 #[cfg(feature = "experimental-inspect")]
686 const OUTPUT_TYPE: PyStaticExpr = PyBaseException::TYPE_HINT;
687
688 #[inline]
689 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
690 Ok(self.into_value(py).into_bound(py))
691 }
692}
693
694impl<'py> IntoPyObject<'py> for &PyErr {
695 type Target = PyBaseException;
696 type Output = Bound<'py, Self::Target>;
697 type Error = Infallible;
698
699 #[cfg(feature = "experimental-inspect")]
700 const OUTPUT_TYPE: PyStaticExpr = PyErr::OUTPUT_TYPE;
701
702 #[inline]
703 fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
704 self.clone_ref(py).into_pyobject(py)
705 }
706}
707
708/// Python exceptions that can be converted to [`PyErr`].
709///
710/// This is used to implement [`From<Bound<'_, T>> for PyErr`].
711///
712/// Users should not need to implement this trait directly. It is implemented automatically in the
713/// [`crate::import_exception!`] and [`crate::create_exception!`] macros.
714pub trait ToPyErr {}
715
716impl<'py, T> std::convert::From<Bound<'py, T>> for PyErr
717where
718 T: ToPyErr,
719{
720 #[inline]
721 fn from(err: Bound<'py, T>) -> PyErr {
722 PyErr::from_value(err.into_any())
723 }
724}
725
726/// Returns Ok if the error code is not -1.
727#[inline]
728pub(crate) fn error_on_minusone<T: SignedInteger>(py: Python<'_>, result: T) -> PyResult<()> {
729 if result != T::MINUS_ONE {
730 Ok(())
731 } else {
732 Err(PyErr::fetch(py))
733 }
734}
735
736pub(crate) trait SignedInteger: Eq {
737 const MINUS_ONE: Self;
738}
739
740macro_rules! impl_signed_integer {
741 ($t:ty) => {
742 impl SignedInteger for $t {
743 const MINUS_ONE: Self = -1;
744 }
745 };
746}
747
748impl_signed_integer!(i8);
749impl_signed_integer!(i16);
750impl_signed_integer!(i32);
751impl_signed_integer!(i64);
752impl_signed_integer!(i128);
753impl_signed_integer!(isize);
754
755#[cfg(test)]
756mod tests {
757 use super::PyErrState;
758 use crate::exceptions::{self, PyTypeError, PyValueError};
759 use crate::impl_::pyclass::{value_of, IsSend, IsSync};
760 use crate::test_utils::assert_warnings;
761 use crate::{PyErr, PyTypeInfo, Python};
762
763 #[test]
764 fn no_error() {
765 assert!(Python::attach(PyErr::take).is_none());
766 }
767
768 #[test]
769 fn set_valueerror() {
770 Python::attach(|py| {
771 let err: PyErr = exceptions::PyValueError::new_err("some exception message");
772 assert!(err.is_instance_of::<exceptions::PyValueError>(py));
773 err.restore(py);
774 assert!(PyErr::occurred(py));
775 let err = PyErr::fetch(py);
776 assert!(err.is_instance_of::<exceptions::PyValueError>(py));
777 assert_eq!(err.to_string(), "ValueError: some exception message");
778 })
779 }
780
781 #[test]
782 fn invalid_error_type() {
783 Python::attach(|py| {
784 let err: PyErr = PyErr::new::<crate::types::PyString, _>(());
785 assert!(err.is_instance_of::<exceptions::PyTypeError>(py));
786 err.restore(py);
787 let err = PyErr::fetch(py);
788
789 assert!(err.is_instance_of::<exceptions::PyTypeError>(py));
790 assert_eq!(
791 err.to_string(),
792 "TypeError: exceptions must derive from BaseException"
793 );
794 })
795 }
796
797 #[test]
798 fn set_typeerror() {
799 Python::attach(|py| {
800 let err: PyErr = exceptions::PyTypeError::new_err(());
801 err.restore(py);
802 assert!(PyErr::occurred(py));
803 drop(PyErr::fetch(py));
804 });
805 }
806
807 #[test]
808 #[should_panic(expected = "new panic")]
809 fn fetching_panic_exception_resumes_unwind() {
810 use crate::panic::PanicException;
811
812 Python::attach(|py| {
813 let err: PyErr = PanicException::new_err("new panic");
814 err.restore(py);
815 assert!(PyErr::occurred(py));
816
817 // should resume unwind
818 let _ = PyErr::fetch(py);
819 });
820 }
821
822 #[test]
823 #[should_panic(expected = "new panic")]
824 #[cfg(not(Py_3_12))]
825 fn fetching_normalized_panic_exception_resumes_unwind() {
826 use crate::panic::PanicException;
827
828 Python::attach(|py| {
829 let err: PyErr = PanicException::new_err("new panic");
830 // Restoring an error doesn't normalize it before Python 3.12,
831 // so we have to explicitly test this case.
832 let _ = err.normalized(py);
833 err.restore(py);
834 assert!(PyErr::occurred(py));
835
836 // should resume unwind
837 let _ = PyErr::fetch(py);
838 });
839 }
840
841 #[test]
842 fn err_debug() {
843 // Debug representation should be like the following (without the newlines):
844 // PyErr {
845 // type: <class 'Exception'>,
846 // value: Exception('banana'),
847 // traceback: Some(\"Traceback (most recent call last):\\n File \\\"<string>\\\", line 1, in <module>\\n\")
848 // }
849
850 Python::attach(|py| {
851 let err = py
852 .run(c"raise Exception('banana')", None, None)
853 .expect_err("raising should have given us an error");
854
855 let debug_str = format!("{err:?}");
856 assert!(debug_str.starts_with("PyErr { "));
857 assert!(debug_str.ends_with(" }"));
858
859 // Strip "PyErr { " and " }". Split into 3 substrings to separate type,
860 // value, and traceback while not splitting the string within traceback.
861 let mut fields = debug_str["PyErr { ".len()..debug_str.len() - 2].splitn(3, ", ");
862
863 assert_eq!(fields.next().unwrap(), "type: <class 'Exception'>");
864 assert_eq!(fields.next().unwrap(), "value: Exception('banana')");
865 assert_eq!(
866 fields.next().unwrap(),
867 "traceback: Some(\"Traceback (most recent call last):\\n File \\\"<string>\\\", line 1, in <module>\\n\")"
868 );
869
870 assert!(fields.next().is_none());
871 });
872 }
873
874 #[test]
875 fn err_display() {
876 Python::attach(|py| {
877 let err = py
878 .run(c"raise Exception('banana')", None, None)
879 .expect_err("raising should have given us an error");
880 assert_eq!(err.to_string(), "Exception: banana");
881 });
882 }
883
884 #[test]
885 fn test_pyerr_send_sync() {
886 assert!(value_of!(IsSend, PyErr));
887 assert!(value_of!(IsSync, PyErr));
888
889 assert!(value_of!(IsSend, PyErrState));
890 assert!(value_of!(IsSync, PyErrState));
891 }
892
893 #[test]
894 fn test_pyerr_matches() {
895 Python::attach(|py| {
896 let err = PyErr::new::<PyValueError, _>("foo");
897 assert!(err.matches(py, PyValueError::type_object(py)).unwrap());
898
899 assert!(err
900 .matches(
901 py,
902 (PyValueError::type_object(py), PyTypeError::type_object(py))
903 )
904 .unwrap());
905
906 assert!(!err.matches(py, PyTypeError::type_object(py)).unwrap());
907
908 // String is not a valid exception class, so we should get a TypeError
909 let err: PyErr = PyErr::from_type(crate::types::PyString::type_object(py), "foo");
910 assert!(err.matches(py, PyTypeError::type_object(py)).unwrap());
911 })
912 }
913
914 #[test]
915 fn test_pyerr_cause() {
916 Python::attach(|py| {
917 let err = py
918 .run(c"raise Exception('banana')", None, None)
919 .expect_err("raising should have given us an error");
920 assert!(err.cause(py).is_none());
921
922 let err = py
923 .run(
924 c"raise Exception('banana') from Exception('apple')",
925 None,
926 None,
927 )
928 .expect_err("raising should have given us an error");
929 let cause = err
930 .cause(py)
931 .expect("raising from should have given us a cause");
932 assert_eq!(cause.to_string(), "Exception: apple");
933
934 err.set_cause(py, None);
935 assert!(err.cause(py).is_none());
936
937 let new_cause = exceptions::PyValueError::new_err("orange");
938 err.set_cause(py, Some(new_cause));
939 let cause = err
940 .cause(py)
941 .expect("set_cause should have given us a cause");
942 assert_eq!(cause.to_string(), "ValueError: orange");
943 });
944 }
945
946 #[test]
947 fn warnings() {
948 use crate::types::any::PyAnyMethods;
949 // Note: although the warning filter is interpreter global, keeping the
950 // GIL locked should prevent effects to be visible to other testing
951 // threads.
952 Python::attach(|py| {
953 let cls = py.get_type::<exceptions::PyUserWarning>();
954
955 // Reset warning filter to default state
956 let warnings = py.import("warnings").unwrap();
957 warnings.call_method0("resetwarnings").unwrap();
958
959 // First, test the warning is emitted
960 assert_warnings!(
961 py,
962 { PyErr::warn(py, &cls, c"I am warning you", 0).unwrap() },
963 [(exceptions::PyUserWarning, "I am warning you")]
964 );
965
966 // Test with raising
967 warnings
968 .call_method1("simplefilter", ("error", &cls))
969 .unwrap();
970 PyErr::warn(py, &cls, c"I am warning you", 0).unwrap_err();
971
972 // Test with error for an explicit module
973 warnings.call_method0("resetwarnings").unwrap();
974 warnings
975 .call_method1("filterwarnings", ("error", "", &cls, "pyo3test"))
976 .unwrap();
977
978 // This has the wrong module and will not raise, just be emitted
979 assert_warnings!(
980 py,
981 { PyErr::warn(py, &cls, c"I am warning you", 0).unwrap() },
982 [(exceptions::PyUserWarning, "I am warning you")]
983 );
984
985 let err = PyErr::warn_explicit(
986 py,
987 &cls,
988 c"I am warning you",
989 c"pyo3test.py",
990 427,
991 None,
992 None,
993 )
994 .unwrap_err();
995 assert!(err
996 .value(py)
997 .getattr("args")
998 .unwrap()
999 .get_item(0)
1000 .unwrap()
1001 .eq("I am warning you")
1002 .unwrap());
1003
1004 // Finally, reset filter again
1005 warnings.call_method0("resetwarnings").unwrap();
1006 });
1007 }
1008
1009 #[test]
1010 #[cfg(Py_3_11)]
1011 fn test_add_note() {
1012 use crate::types::any::PyAnyMethods;
1013 Python::attach(|py| {
1014 let err = PyErr::new::<exceptions::PyValueError, _>("original error");
1015 err.add_note(py, "additional context").unwrap();
1016
1017 let notes = err.value(py).getattr("__notes__").unwrap();
1018 assert_eq!(notes.len().unwrap(), 1);
1019 assert_eq!(
1020 notes.get_item(0).unwrap().extract::<String>().unwrap(),
1021 "additional context"
1022 );
1023 });
1024 }
1025}