How to catch panic for a async function?

I want to get panic for a async function which looks like below:

        let x = a_sync_function(param1, param2).await?;
       // the return of `a_sync_function` is : Result<Vec<serde_json::Value>, Box<dyn Error>>

if there is any panic for above code running, I want to catch the panic and run another code;
how shall I do this?

If the task panics, the error is a JoinError that contains the panic:

You can use FutureExt in futures::future - Rust which is the async equivalent of std::panic::catch_unwind

2 Likes

I have tried, but get below error:

`dyn StdError` cannot be sent between threads safely
the trait `Send` is not implemented for `dyn StdError`
required for `Unique<dyn StdError>` to implement `Send`

That's not related to the panic catching thing - most executors will require the Future you spawn to be Send so they can be executed on a multi-threaded runtime.

That error message indicates you're probably using a Box<dyn std::error::Error> (or something that contains one) as your function's error type, and Box<dyn std::error::Error> isn't Send. You'll typically want to use Box<dyn std::error::Error + Send + Sync> when working with async code.

3 Likes

Thank you, I have modified this as below according to your advice:

let x_handle: tokio::task::JoinHandle<Result<Vec<serde_json::Value>, Box<dyn Error + Send + Sync>> = tokio::spawn(async {
            let x = a_sync_function(param1, param2).await;
            Ok(x)
        });

Then I get this error on async as below:

Syntax Error: expected value parameterrust-analyzersyntax-error
Syntax Error: expected R_PARENrust-analyzersyntax-error
Syntax Error: expected R_ANGLErust-analyzersyntax-error
Syntax Error: expected SEMICOLONrust-analyzersyntax-error
expected type, found keyword `async`
expected typerustcClick for full compiler diagnostic

Looks like you have unbalanced angle brackets in the type.

it is balanced.

Reformatted:

tokio::task::JoinHandle<
    Result<
        Vec<serde_json::Value>,
        Box<dyn Error + Send + Sync>
    >

So it actually isn't, and the full error from cargo check would likely hint you on that.

2 Likes

it is the same;

TLDR: you are missing a > in the type.

1 Like

thank you

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.