Skip to main content

sqlload_python_host/host/main/
error_text.rs

1//! A Python exception as the engine reports it.
2
3use pyo3::types::{PyStringMethods, PyTracebackMethods, PyTypeMethods};
4use pyo3::{PyErr, Python};
5
6/// A Python exception as one line: its type and message, then where in the user's code it was raised.
7pub fn error_text(error: &PyErr) -> String {
8    Python::attach(|py| {
9        let place = error
10            .traceback(py)
11            .and_then(|traceback| match traceback.format() {
12                Ok(text) => text
13                    .lines()
14                    .rfind(|line| line.trim_start().starts_with("File "))
15                    .map(|line| format!(" ({})", line.trim())),
16                Err(_) => None,
17            })
18            .unwrap_or_default();
19        let kind = error.get_type(py).name().map_or_else(
20            |_| "Exception".to_owned(),
21            |name| name.to_string_lossy().into_owned(),
22        );
23        format!("{kind}: {}{place}", error.value(py))
24    })
25}