我想编写一个读取文件内容的函数,如果失败则引发错误。我想从 python 脚本调用这个函数,所以我在下面提到了一些 Python,以防它可能相关。
正如我尝试在评论中展示的那样,可能会发生更多的工作来引发其他类型的错误,所以如果可能的话,如果在 Rust(?) 中可能的话,我想使用一个通用错误。如何返回错误,以便可以处理它并将其包装在 python 错误中,如图所示do_work
?不确定我导致以下错误的方法是否朝着正确的方向发展。
fn work_with_text() -> Result<(), dyn std::error::Error> {
let content = match std::fs::read_to_string("text.txt") {
Ok(t) => t,
Err(e) => return Err(e),
};
// do something with content that may cause another type of error (rusqlite error)
Ok(())
}
#[pyfunction]
fn do_work(_py: Python) -> PyResult<u32> {
match work_with_text() {
Ok(_) => (0),
Err(e) => {
let gil = Python::acquire_gil();
let py = gil.python();
let error_message = format!("Error happened {}", e.to_string());
PyIOError::new_err(error_message).restore(py);
return Err(PyErr::fetch(py));
}
};
// ...
}
错误:
1 | ... fn work_with_text() -> Result<(), dyn std::error::Error> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `(dyn std::error::Error + 'static)`