Skip to content

Commit 0445861

Browse files
Add clear backtrace on PyO3 error during main.py initialisation
1 parent a215502 commit 0445861

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

src/error.rs

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
// git clone https://github.com/marcomq/tauri-plugin-python
55

66
#[cfg(feature = "pyo3")]
7-
use pyo3::PyErr;
7+
use pyo3::{prelude::*, PyErr};
88
use serde::{ser::Serializer, Serialize};
99

1010
pub type Result<T> = std::result::Result<T, Error>;
@@ -63,9 +63,24 @@ impl From<rustpython_vm::PyRef<rustpython_vm::builtins::PyBaseException>> for Er
6363
#[cfg(feature = "pyo3")]
6464
impl From<PyErr> for Error {
6565
fn from(error: PyErr) -> Self {
66-
let msg = error.to_string();
67-
println!("error: {}", &msg);
68-
Error::String(msg)
66+
let error_msg = match pyo3::Python::with_gil(|py| {
67+
let traceback_module = py.import("traceback")?;
68+
let traceback_object = error
69+
.traceback(py)
70+
.ok_or(pyo3::exceptions::PyWarning::new_err("No traceback found."))
71+
.inspect(|r| println!("DEBUG: traceback extracted {:?}", r))?;
72+
let format_traceback = traceback_module.getattr("format_tb")?;
73+
format_traceback
74+
.call1((traceback_object,))
75+
.and_then(|r| r.extract::<Vec<String>>())
76+
}) {
77+
Ok(formatted) => formatted.join(""),
78+
Err(_) => {
79+
error.to_string() // Fall back to simple error message
80+
}
81+
};
82+
83+
Error::String(error_msg)
6984
}
7085
}
7186

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ sys.path = sys.path + [{}]
107107
code
108108
);
109109
py_lib::run_python_internal(path_import, "main.py".into())
110-
.unwrap_or_else(|e| panic!("Error '{e}' initializing main.py"));
110+
.unwrap_or_else(|e| panic!("Error initializing main.py:\n\n{e}\n"));
111111
}
112112

113113
/// Initializes the plugin.

0 commit comments

Comments
 (0)