I want to write a function that reads the contents of a file, and raises an error if it fails. I want to call this function from a python script, so I'm including some mentions of Python below in case it might be relevant.
As I have tried showing in the comments, more work might happen that raises other types of errors, so if it is possible I would like to use a generic error if this is possible in Rust(?). How can I return the error so it can be handled and wrapped in a python error as shown in do_work
? Not sure if my approach that is resulting in the error below is in the right direction.
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));
}
};
// ...
}
error:
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)`
Box<dyn Error>
– ExcuseResult<(), dyn std::error::Error>
instead ofResult<(), std::io::Error>
or juststd::io::Result<()>
? – Flocculantenum Error
with variants for each kind of error. Instead ofdyn std::error::Error
. – FlocculantBox<dyn Error>
is usually fine in an application, or here if they only raise a very generic exception at the python level. – Havocmatch
is a complicated way of writinglet content = read_to_string(...)?;
, and the later will take care of conversions if available & necessary. – HavocBox<dyn Error>
, regardless of library vs application. Every time I've usedBox<dyn Error>
, I've in the future had to rework code, when I needed to handle the individual error kinds. Dealing withBox<dyn Error>
can be quite annoying. – Flocculant