Skip to main content

ErrorToGodot

Trait ErrorToGodot 

pub trait ErrorToGodot<T>: Sized
where T: ToGodot,
{ type Mapped: ToGodot; // Required method fn result_to_godot(result: Result<T, Self>) -> CallOutcome<Self::Mapped>; }
Expand description

Defines how Result<T, E> returned by #[func] is mapped to Godot.

When implemented for a type E, this trait enables Result<T, E> return types in #[func] methods.

§Implementing the trait

The associated type Mapped determines what GDScript sees as the function’s return type. This type can depend on T – the ok-value type of the Result – because the trait is generic over T.

Users then override result_to_godot(), returning a CallOutcome:

§Built-in strategies

See the strat module for all provided implementations, or for inspirations for custom error handling.

§Example: typed Array<T> with 0 or 1 elements

Since the trait is generic over T, custom implementations can require tighter bounds (such as Element) and use a typed Array<T> as the mapped type.

This example returns a 1-element array on success, or a 0-element one on error – a poor man’s Option<T> in GDScript.

use godot::builtin::Array;
use godot::meta::error::{CallOutcome, ErrorToGodot};
use godot::meta::{Element, owned_into_arg};

struct MyError(String);

impl<T: Element> ErrorToGodot<T> for MyError {
    // GDScript sees Array[T] as the #[func]'s return type.
    type Mapped = Array<T>;

    fn result_to_godot(result: Result<T, Self>) -> CallOutcome<Array<T>> {
        // Construct [elem] or [].
        let array = match result {
            Ok(elem) => array![owned_into_arg(elem)],
            Err(_) => Array::new(),
        };

        // We always return a value, never fail the call -> only use CallOutcome::Return.
        CallOutcome::Return(array)
    }
}

GDScript usage:

var result := node.some_fn()  # typed Array[...]
if result.is_empty():
    print("Operation failed")
else:
    var value := result.front()  # typed!

Required Associated Types§

type Mapped: ToGodot

The type to which Result<T, Self> is mapped on Godot side.

Required Methods§

fn result_to_godot(result: Result<T, Self>) -> CallOutcome<Self::Mapped>

Map an owned Result to a Godot return value or an unexpected-error message.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

§

impl<T> ErrorToGodot<T> for ()
where T: ToGodot,

Error strategy that returns null on error, instead of making the call fail.

Use this when an absent value is a normal outcome that GDScript should handle, for example a missing save file for a new player. GDScript receives a Variant containing either the value or null.

Since () discards all error information, use .map_err(|_| ())? to propagate any error into it.

§Example

use godot::prelude::*;

#[godot_api]
impl PlayerData {
    // Returns the high score from a save file, or null if absent or unreadable.
    // A missing file is normal for new players -- GDScript handles null gracefully.
    #[func]
    fn load_high_score(&self, save_path: String) -> Result<i64, ()> {
        let text = std::fs::read_to_string(save_path).map_err(|_| ())?;
        text.trim().parse::<i64>().map_err(|_| ())
    }
}

GDScript usage:

var score = player.load_high_score("user://highscore.dat")
if score == null:
    # New player, no save file yet.

Implementors§

§

impl<T> ErrorToGodot<T> for Error
where T: ToGodot,

§

impl<T> ErrorToGodot<T> for Unexpected
where T: ToGodot,

§

type Mapped = T