1use std::error::Error;
4use std::fmt::{Display, Formatter};
5
6use bevy_ecs::entity::Entity;
7
8#[derive(Clone, Debug, PartialEq, Eq)]
10pub enum AppError {
11 InvalidFixedDelta,
12 DuplicatePlugin(&'static str),
13 HierarchyCycle {
14 child: Entity,
15 parent: Entity,
16 },
17 MissingEntity(Entity),
18 PluginSetup {
19 plugin: &'static str,
20 message: String,
21 },
22}
23
24impl Display for AppError {
25 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
26 match self {
27 Self::InvalidFixedDelta => formatter.write_str("fixed delta must be greater than zero"),
28 Self::DuplicatePlugin(name) => write!(formatter, "plugin `{name}` was already added"),
29 Self::HierarchyCycle { child, parent } => write!(
30 formatter,
31 "parenting {child:?} beneath {parent:?} would create a hierarchy cycle"
32 ),
33 Self::MissingEntity(entity) => write!(formatter, "entity {entity:?} does not exist"),
34 Self::PluginSetup { plugin, message } => {
35 write!(formatter, "plugin `{plugin}` setup failed: {message}")
36 }
37 }
38 }
39}
40
41impl Error for AppError {}
42
43#[cfg(test)]
44mod tests {
45 use std::error::Error;
46
47 use bevy_ecs::entity::Entity;
48
49 use super::AppError;
50
51 #[test]
52 fn errors_preserve_entity_and_plugin_context() {
53 let entity = Entity::from_bits(1);
54 let missing = AppError::MissingEntity(entity);
55 assert!(missing.to_string().contains(&format!("{entity:?}")));
56
57 let setup = AppError::PluginSetup {
58 plugin: "TestPlugin",
59 message: "invalid configuration".into(),
60 };
61 assert_eq!(
62 setup.to_string(),
63 "plugin `TestPlugin` setup failed: invalid configuration"
64 );
65
66 let _: &dyn Error = &setup;
67 }
68}