bevy_app/
panic_handler.rs

1//! This module provides panic handlers for [Bevy](https://bevyengine.org)
2//! apps, and automatically configures platform specifics (i.e. Wasm or Android).
3//!
4//! By default, the [`PanicHandlerPlugin`] from this crate is included in Bevy's `DefaultPlugins`.
5//!
6//! For more fine-tuned control over panic behavior, disable the [`PanicHandlerPlugin`] or
7//! `DefaultPlugins` during app initialization.
8
9use crate::{App, Plugin};
10
11/// Adds sensible panic handlers to Apps. This plugin is part of the `DefaultPlugins`. Adding
12/// this plugin will setup a panic hook appropriate to your target platform:
13/// * On Wasm, uses [`console_error_panic_hook`](https://crates.io/crates/console_error_panic_hook), logging
14///   to the browser console.
15/// * Other platforms are currently not setup.
16///
17/// ```no_run
18/// # use bevy_app::{App, NoopPluginGroup as MinimalPlugins, PluginGroup, PanicHandlerPlugin};
19/// fn main() {
20///     App::new()
21///         .add_plugins(MinimalPlugins)
22///         .add_plugins(PanicHandlerPlugin)
23///         .run();
24/// }
25/// ```
26///
27/// If you want to setup your own panic handler, you should disable this
28/// plugin from `DefaultPlugins`:
29/// ```no_run
30/// # use bevy_app::{App, NoopPluginGroup as DefaultPlugins, PluginGroup, PanicHandlerPlugin};
31/// fn main() {
32///     App::new()
33///         .add_plugins(DefaultPlugins.build().disable::<PanicHandlerPlugin>())
34///         .run();
35/// }
36/// ```
37#[derive(Default)]
38pub struct PanicHandlerPlugin;
39
40impl Plugin for PanicHandlerPlugin {
41    fn build(&self, _app: &mut App) {
42        #[cfg(feature = "std")]
43        {
44            static SET_HOOK: std::sync::Once = std::sync::Once::new();
45            SET_HOOK.call_once(|| {
46                cfg_if::cfg_if! {
47                    if #[cfg(all(target_arch = "wasm32", feature = "web"))] {
48                        // This provides better panic handling in JS engines (displays the panic message and improves the backtrace).
49                        std::panic::set_hook(alloc::boxed::Box::new(console_error_panic_hook::hook));
50                    } else if #[cfg(feature = "error_panic_hook")] {
51                        let current_hook = std::panic::take_hook();
52                        std::panic::set_hook(alloc::boxed::Box::new(
53                            bevy_ecs::error::bevy_error_panic_hook(current_hook),
54                        ));
55                    }
56                    // Otherwise use the default target panic hook - Do nothing.
57                }
58            });
59        }
60    }
61}