world_dispatcher/
error.rs

1use crate::*;
2
3/// The types of errors a `System` can create.
4#[derive(Debug)]
5pub enum EcsError {
6    /// A resource was not initialized in the `World` but the
7    /// `System` tries to access it.
8    ///
9    /// Usually, this means no dispatcher was used and `World::initialize`
10    /// was not called.
11    NotInitialized,
12    /// The requested resource is already borrowed.
13    /// This error is created if the `System` tries to read a resource that
14    /// has already been mutably borrowed.
15    /// It can also happen when trying to mutably borrow a resource that is
16    /// already being read.
17    ///
18    /// This error should not occur during normal use, as the dispatchers
19    /// can recover easily.
20    AlreadyBorrowed,
21    /// The execution of the dispatcher failed and returned one or more errors.
22    DispatcherExecutionFailed(Vec<EcsError>),
23    /// This variant is for user-defined errors.
24    /// To create an error of this type easily, use the `system_error!` macro.
25    SystemError(Box<dyn Error+Send>),
26}
27
28/// The result of a `System`'s execution.
29/// Returns Ok(()) on success, `EcsError` on failure.
30/// To return a custom error from a system, use the
31/// `system_error!` macro.
32pub type SystemResult = Result<(), EcsError>;
33
34/// Returns a custom error from a `System` during execution.
35#[macro_export]
36macro_rules! system_error {
37    ($err:expr) => {
38        return Err(EcsError::SystemError(Box::new($err)));
39    };
40}
41
42#[cfg(test)]
43mod tests {
44    use crate::*;
45    use wasm_bindgen_test::*;
46
47    #[test]
48    #[wasm_bindgen_test]
49    fn system_return_custom_error() {
50        #[derive(Debug)]
51        struct CustomError;
52        impl std::fmt::Display for CustomError {
53            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
54                write!(f, "Custom error crash")
55            }
56        }
57        impl Error for CustomError {}
58        fn sys() -> SystemResult {
59            system_error!(CustomError)
60        }
61        let mut s = sys.system();
62        let result = s.run(&World::default());
63        match result {
64            Err(EcsError::SystemError(err)) => assert_eq!(err.to_string(), "Custom error crash"),
65            _ => unreachable!(),
66        }
67    }
68}