Skip to content

Catch the panics within spawned async tasks #314

Open
@SteveLauC

Description

@SteveLauC

Is your feature request related to a problem? Please describe.

Currently, a panic!() within spawned tasks kills the runtime thread because we are not catching it. Tokio, by default, catches all the panics from the spawned task, and a configuration entry is provided to turn this off.

Perhaps Monoio could also catch panics and allow users to enable or disable this behavior through a configuration entry.

Describe the solution you'd like

The following code snippet implements a spawn() that catches the panic and forwards it to JoinHandle:

use futures::{FutureExt, TryFutureExt};
use monoio::task::JoinHandle;
use std::{any::Any, future::Future};

fn spawn_with_panic_caught<F>(
    future: F,
) -> JoinHandle<Result<F::Output, Box<dyn Any + 'static>>>
where
    F: Future + 'static,
    F::Output: 'static,
{
    let future = std::panic::AssertUnwindSafe(future)
        .catch_unwind()
        .map_err(|e| e as Box<dyn Any + 'static>);

    monoio::spawn(future)
}

Describe alternatives you've considered

None

Additional context

None

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions