Custom Errors in GDScript

# A custom error type usually has the suffix "Error".
class ArgError:
    var arg: int
    var message: String

    func _init(arg: int, message: String):
        self.arg = arg
        self.message = message

    # Adding this to_string method makes ArgError behave like an error.
    func _to_string() -> String:
        return "%d - %s" % [arg, message]

func f(arg: int) -> Array:
    if arg == 42:
        # Return our custom error.
        return [-1, ArgError.new(arg, "can't work with it")]
    return [arg + 3, null]

func _ready():
    var result = f(42)
    var err = result[1]
    
    # In GDScript, we use `is` to check if an object is an instance of a class
    if err is ArgError:
        print(err.arg)
        print(err.message)
    else:
        print("err doesn't match ArgError")

This script demonstrates how to create and use custom error types in GDScript. Here’s a breakdown of the code:

  1. We define a custom ArgError class to represent an argument error. It has two properties: arg (the problematic argument) and message (a description of the error).

  2. The _to_string() method is implemented to provide a string representation of the error. This is similar to the Error() method in Go.

  3. The f() function demonstrates how to return and use the custom error. If the argument is 42, it returns an array with -1 and an ArgError instance. Otherwise, it returns the argument plus 3 and null (which represents no error).

  4. In the _ready() function (which is called automatically when the script is loaded), we call f(42) and check if the returned error is an instance of ArgError.

  5. GDScript doesn’t have a direct equivalent to Go’s errors.As(). Instead, we use the is keyword to check if an object is an instance of a specific class.

To run this script:

  1. Create a new script in your Godot project.
  2. Copy the above code into the script.
  3. Attach the script to a Node in your scene.
  4. Run the scene.

The output should be:

42
can't work with it

This example shows how to create and use custom error types in GDScript, providing a way to handle specific error conditions in your code.