Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catch the panics within spawned async tasks #314

Open
SteveLauC opened this issue Oct 28, 2024 · 1 comment · May be fixed by #319
Open

Catch the panics within spawned async tasks #314

SteveLauC opened this issue Oct 28, 2024 · 1 comment · May be fixed by #319
Labels
F-feature-request feature request

Comments

@SteveLauC
Copy link
Contributor

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

@SteveLauC SteveLauC added the F-feature-request feature request label Oct 28, 2024
@SteveLauC
Copy link
Contributor Author

SteveLauC commented Oct 28, 2024

Based on the discussion in the feishu group, this feature request is accepted, I will file a PR to implement it.

@SteveLauC SteveLauC linked a pull request Nov 2, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
F-feature-request feature request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant