|
| 1 | +use alloc::boxed::Box; |
| 2 | +use core::{ |
| 3 | + error::Error, |
| 4 | + fmt::{Debug, Display}, |
| 5 | +}; |
| 6 | + |
| 7 | +/// The built in "universal" Bevy error type. This has a blanket [`From`] impl for any type that implements Rust's [`Error`], |
| 8 | +/// meaning it can be used as a "catch all" error. |
| 9 | +/// |
| 10 | +/// # Backtraces |
| 11 | +/// |
| 12 | +/// When used with the `backtrace` Cargo feature, it will capture a backtrace when the error is constructed (generally in the [`From`] impl]). |
| 13 | +/// When printed, the backtrace will be displayed. By default, the backtrace will be trimmed down to filter out noise. To see the full backtrace, |
| 14 | +/// set the `BEVY_BACKTRACE=full` environment variable. |
| 15 | +/// |
| 16 | +/// # Usage |
| 17 | +/// |
| 18 | +/// ``` |
| 19 | +/// # use bevy_ecs::prelude::*; |
| 20 | +/// |
| 21 | +/// fn fallible_system() -> Result<(), BevyError> { |
| 22 | +/// // This will result in Rust's built-in ParseIntError, which will automatically |
| 23 | +/// // be converted into a BevyError. |
| 24 | +/// let parsed: usize = "I am not a number".parse()?; |
| 25 | +/// Ok(()) |
| 26 | +/// } |
| 27 | +/// ``` |
| 28 | +pub struct BevyError { |
| 29 | + inner: Box<InnerBevyError>, |
| 30 | +} |
| 31 | + |
| 32 | +impl BevyError { |
| 33 | + /// Attempts to downcast the internal error to the given type. |
| 34 | + pub fn downcast_ref<E: Error + 'static>(&self) -> Option<&E> { |
| 35 | + self.inner.error.downcast_ref::<E>() |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/// This type exists (rather than having a `BevyError(Box<dyn InnerBevyError)`) to make [`BevyError`] use a "thin pointer" instead of |
| 40 | +/// a "fat pointer", which reduces the size of our Result by a usize. This does introduce an extra indirection, but error handling is a "cold path". |
| 41 | +/// We don't need to optimize it to that degree. |
| 42 | +/// PERF: We could probably have the best of both worlds with a "custom vtable" impl, but thats not a huge priority right now and the code simplicity |
| 43 | +/// of the current impl is nice. |
| 44 | +struct InnerBevyError { |
| 45 | + error: Box<dyn Error + Send + Sync + 'static>, |
| 46 | + #[cfg(feature = "backtrace")] |
| 47 | + backtrace: std::backtrace::Backtrace, |
| 48 | +} |
| 49 | + |
| 50 | +// NOTE: writing the impl this way gives us From<&str> ... nice! |
| 51 | +impl<E> From<E> for BevyError |
| 52 | +where |
| 53 | + Box<dyn Error + Send + Sync + 'static>: From<E>, |
| 54 | +{ |
| 55 | + #[cold] |
| 56 | + fn from(error: E) -> Self { |
| 57 | + BevyError { |
| 58 | + inner: Box::new(InnerBevyError { |
| 59 | + error: error.into(), |
| 60 | + #[cfg(feature = "backtrace")] |
| 61 | + backtrace: std::backtrace::Backtrace::capture(), |
| 62 | + }), |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +impl Display for BevyError { |
| 68 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 69 | + writeln!(f, "{}", self.inner.error)?; |
| 70 | + Ok(()) |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +impl Debug for BevyError { |
| 75 | + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { |
| 76 | + writeln!(f, "{:?}", self.inner.error)?; |
| 77 | + #[cfg(feature = "backtrace")] |
| 78 | + { |
| 79 | + let backtrace = &self.inner.backtrace; |
| 80 | + if let std::backtrace::BacktraceStatus::Captured = backtrace.status() { |
| 81 | + let full_backtrace = std::env::var("BEVY_BACKTRACE").is_ok_and(|val| val == "full"); |
| 82 | + |
| 83 | + let backtrace_str = alloc::string::ToString::to_string(backtrace); |
| 84 | + let mut skip_next_location_line = false; |
| 85 | + for line in backtrace_str.split('\n') { |
| 86 | + if !full_backtrace { |
| 87 | + if skip_next_location_line { |
| 88 | + if line.starts_with(" at") { |
| 89 | + continue; |
| 90 | + } |
| 91 | + skip_next_location_line = false; |
| 92 | + } |
| 93 | + if line.contains("std::backtrace_rs::backtrace::") { |
| 94 | + skip_next_location_line = true; |
| 95 | + continue; |
| 96 | + } |
| 97 | + if line.contains("std::backtrace::Backtrace::") { |
| 98 | + skip_next_location_line = true; |
| 99 | + continue; |
| 100 | + } |
| 101 | + if line.contains("<bevy_ecs::error::bevy_error::BevyError as core::convert::From<E>>::from") { |
| 102 | + skip_next_location_line = true; |
| 103 | + continue; |
| 104 | + } |
| 105 | + if line.contains("<core::result::Result<T,F> as core::ops::try_trait::FromResidual<core::result::Result<core::convert::Infallible,E>>>::from_residual") { |
| 106 | + skip_next_location_line = true; |
| 107 | + continue; |
| 108 | + } |
| 109 | + if line.contains("__rust_begin_short_backtrace") { |
| 110 | + break; |
| 111 | + } |
| 112 | + if line.contains("bevy_ecs::observer::Observers::invoke::{{closure}}") { |
| 113 | + break; |
| 114 | + } |
| 115 | + } |
| 116 | + writeln!(f, "{}", line)?; |
| 117 | + } |
| 118 | + if !full_backtrace { |
| 119 | + if std::thread::panicking() { |
| 120 | + SKIP_NORMAL_BACKTRACE.store(1, core::sync::atomic::Ordering::Relaxed); |
| 121 | + } |
| 122 | + writeln!(f, "{FILTER_MESSAGE}")?; |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + Ok(()) |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +#[cfg(feature = "backtrace")] |
| 132 | +const FILTER_MESSAGE: &str = "note: Some \"noisy\" backtrace lines have been filtered out. Run with `BEVY_BACKTRACE=full` for a verbose backtrace."; |
| 133 | + |
| 134 | +#[cfg(feature = "backtrace")] |
| 135 | +static SKIP_NORMAL_BACKTRACE: core::sync::atomic::AtomicUsize = |
| 136 | + core::sync::atomic::AtomicUsize::new(0); |
| 137 | + |
| 138 | +/// When called, this will skip the currently configured panic hook when a [`BevyError`] backtrace has already been printed. |
| 139 | +#[cfg(feature = "std")] |
| 140 | +pub fn bevy_error_panic_hook( |
| 141 | + current_hook: impl Fn(&std::panic::PanicHookInfo), |
| 142 | +) -> impl Fn(&std::panic::PanicHookInfo) { |
| 143 | + move |info| { |
| 144 | + if SKIP_NORMAL_BACKTRACE.load(core::sync::atomic::Ordering::Relaxed) > 0 { |
| 145 | + if let Some(payload) = info.payload().downcast_ref::<&str>() { |
| 146 | + std::println!("{payload}"); |
| 147 | + } else if let Some(payload) = info.payload().downcast_ref::<alloc::string::String>() { |
| 148 | + std::println!("{payload}"); |
| 149 | + } |
| 150 | + SKIP_NORMAL_BACKTRACE.store(0, core::sync::atomic::Ordering::Relaxed); |
| 151 | + return; |
| 152 | + } |
| 153 | + |
| 154 | + current_hook(info); |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +#[cfg(test)] |
| 159 | +mod tests { |
| 160 | + |
| 161 | + #[test] |
| 162 | + #[cfg(not(miri))] // miri backtraces are weird |
| 163 | + #[cfg(not(windows))] // the windows backtrace in this context is ... unhelpful and not worth testing |
| 164 | + fn filtered_backtrace_test() { |
| 165 | + fn i_fail() -> crate::error::Result { |
| 166 | + let _: usize = "I am not a number".parse()?; |
| 167 | + Ok(()) |
| 168 | + } |
| 169 | + |
| 170 | + // SAFETY: this is not safe ... this test could run in parallel with another test |
| 171 | + // that writes the environment variable. We either accept that so we can write this test, |
| 172 | + // or we don't. |
| 173 | + |
| 174 | + unsafe { std::env::set_var("RUST_BACKTRACE", "1") }; |
| 175 | + |
| 176 | + let error = i_fail().err().unwrap(); |
| 177 | + let debug_message = alloc::format!("{error:?}"); |
| 178 | + let mut lines = debug_message.lines().peekable(); |
| 179 | + assert_eq!( |
| 180 | + "ParseIntError { kind: InvalidDigit }", |
| 181 | + lines.next().unwrap() |
| 182 | + ); |
| 183 | + |
| 184 | + // On mac backtraces can start with Backtrace::create |
| 185 | + let mut skip = false; |
| 186 | + if let Some(line) = lines.peek() { |
| 187 | + if &line[6..] == "std::backtrace::Backtrace::create" { |
| 188 | + skip = true; |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + if skip { |
| 193 | + lines.next().unwrap(); |
| 194 | + } |
| 195 | + |
| 196 | + let expected_lines = alloc::vec![ |
| 197 | + "bevy_ecs::error::bevy_error::tests::filtered_backtrace_test::i_fail", |
| 198 | + "bevy_ecs::error::bevy_error::tests::filtered_backtrace_test", |
| 199 | + "bevy_ecs::error::bevy_error::tests::filtered_backtrace_test::{{closure}}", |
| 200 | + "core::ops::function::FnOnce::call_once", |
| 201 | + ]; |
| 202 | + |
| 203 | + for expected in expected_lines { |
| 204 | + let line = lines.next().unwrap(); |
| 205 | + assert_eq!(&line[6..], expected); |
| 206 | + let mut skip = false; |
| 207 | + if let Some(line) = lines.peek() { |
| 208 | + if line.starts_with(" at") { |
| 209 | + skip = true; |
| 210 | + } |
| 211 | + } |
| 212 | + |
| 213 | + if skip { |
| 214 | + lines.next().unwrap(); |
| 215 | + } |
| 216 | + } |
| 217 | + |
| 218 | + // on linux there is a second call_once |
| 219 | + let mut skip = false; |
| 220 | + if let Some(line) = lines.peek() { |
| 221 | + if &line[6..] == "core::ops::function::FnOnce::call_once" { |
| 222 | + skip = true; |
| 223 | + } |
| 224 | + } |
| 225 | + if skip { |
| 226 | + lines.next().unwrap(); |
| 227 | + } |
| 228 | + let mut skip = false; |
| 229 | + if let Some(line) = lines.peek() { |
| 230 | + if line.starts_with(" at") { |
| 231 | + skip = true; |
| 232 | + } |
| 233 | + } |
| 234 | + |
| 235 | + if skip { |
| 236 | + lines.next().unwrap(); |
| 237 | + } |
| 238 | + assert_eq!(super::FILTER_MESSAGE, lines.next().unwrap()); |
| 239 | + assert!(lines.next().is_none()); |
| 240 | + } |
| 241 | +} |
0 commit comments