rustasync-awaitpanic

How to catch panic for a async function?


I want to try to catch 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 when above code running, I want to catch the panic and run another code; how shall I do this?


Solution

  • catch_unwind() doesn't take a future, so you cannot use it.

    Luckily, futures has FutureExt::catch_unwind(), that wraps a future with panic catching. Under the hood, it uses catch_unwind() for every poll().

    use futures::FutureExt;
    
    let x = a_sync_function(param1, param2).catch_unwind().await;
    // `x` is now `Result<Result<Vec<serde_json::Value>, Box<dyn Error>>, Box<dyn Any + Send>>`
    // The inner `Result` is the normal return type of the function,
    // the outer `Result` is `Err` if a panic occurred with the panic payload.