Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Error Handling

Pretty much every method of a plugin or a script returns a special type GameResult which is a wrapper over Result<(), GameError>. This allows you to easily handle various errors that may occur during the code execution by applying ? operator.

#![allow(unused)]
fn main() {
#[derive(Visit, Reflect, Default, Debug, Clone, TypeUuidProvider, ComponentProvider)]
#[type_uuid(id = "bf0f9804-56cb-4a2e-beba-93d75371a568")]
#[visit(optional)]
struct MyScript {
    handle: Handle<Node>,
}

impl ScriptTrait for MyScript {
    fn on_update(&mut self, context: &mut ScriptContext) -> GameResult {
        let node = context.scene.graph.try_get(context.handle)?;
        println!("{}", node.name());
        Ok(())
    }
}

#[derive(Visit, Reflect, Debug)]
struct MyPlugin;

impl Plugin for MyPlugin {
    fn init(&mut self, scene_path: Option<&str>, context: PluginContext) -> GameResult {
        // This method can be called at any point in your game, this way you can enable or disable
        // enhanced error data collection when needed.
        enable_backtrace_capture(true);
        Ok(())
    }
}
}

When an error occurs in any of the methods, the engine simply prints it to the log and continues execution as usual. This is the key difference between errors and standard panic mechanism.

The GameError type can hold errors of pretty much any kind, so any error that implements std::error::Error trait can be returned.

Backtrace capture

By default, all errors that may occur during the code execution don’t capture the backtrace, which may significantly complicate tracking of the original source of error. Backtrace capture can be enabled by using enable_backtrace_capture: method.

#![allow(unused)]
fn main() {
#[derive(Visit, Reflect, Debug)]
struct MyPlugin;

impl Plugin for MyPlugin {
    fn init(&mut self, scene_path: Option<&str>, context: PluginContext) -> GameResult {
        // This method can be called at any point in your game, this way you can enable or disable
        // enhanced error data collection when needed.
        enable_backtrace_capture(true);
        Ok(())
    }
}
}

This way the engine will print the error message alongside with the backtrace which points to the exact place where the error originates from.