I would like to catch the possible panic when calling a async function.
I read this documentation : JoinHandle in tokio::task - Rust
and I intend to use this kind of code :
let panics = tokio::spawn(async move {
test.run().await
});
match panics {
// do something according if it is ok or err
...
The run function looks like this :
pub async fn run(&self) -> Result<()> {
...
}
With result like :
pub type Result<T> = core::result::Result<T, Error>;
pub type Error = Box<dyn std::error::Error>;
Actually I got this error :
let panics = tokio::spawn(async move {
| __________________________________------------_^
| | |
| | required by a bound introduced by this call
91 | | test.run().await
92 | | });
| |_____________________^ `dyn StdError` cannot be sent between threads safely
|
= help: the trait `Send` is not implemented for `dyn StdError`
= note: required for `Unique<dyn StdError>` to implement `Send`
I understant that Send must be add somewhere, but I don't know if it is in error type or else ?
If I add like this, I have a lot more error everywhere... :
pub type Error = Box<dyn std::error::Error + Send>;
pub async fn handle(&self) -> Result<()> {
...
let test = Test::new();
let panics = tokio::spawn(async move { test.run().await });
...
handle is a function that I call on a struct.
I have move word because I think that I need to pass the test value. But I do not need to pass &self.
and I have this error :
pub async fn handle(&self) -> Result<()> {
| -----
| |
| `self` is a reference that is only valid in the method body
| let's call the lifetime of this reference `'1`
...
91 | let panics = tokio::spawn(async move { test.run().await });
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| `self` escapes the method body here
| argument requires that `'1` must outlive `'static`
test is a borrow from &self so you can't do that. So either you pass self by value (but then, it is owned by the handle() function) or you find another way.
Thank you. I realise I do not understand this with the error message.
So finally, I make the possibility to clone a Test.
As when a test is configured, we only need its value to pass the test.