Custom Errors in UnrealScript

Custom errors can be implemented in UnrealScript by creating a new class that extends the Object class and implementing a custom ToString() function. Here’s an example that demonstrates this concept:

class ArgError extends Object;

var int arg;
var string message;

function string ToString()
{
    return arg $ " - " $ message;
}

static function ArgError Create(int InArg, string InMessage)
{
    local ArgError NewError;
    NewError = new class'ArgError';
    NewError.arg = InArg;
    NewError.message = InMessage;
    return NewError;
}

This ArgError class serves as our custom error type. The ToString() function is similar to the Error() method in other languages, providing a string representation of the error.

Now, let’s create a function that might return this custom error:

function bool F(int arg, out string ErrorMessage)
{
    if (arg == 42)
    {
        ErrorMessage = ArgError.Create(arg, "can't work with it").ToString();
        return false;
    }
    return true;
}

In UnrealScript, we don’t have a built-in error handling mechanism like try-catch blocks. Instead, we use boolean return values to indicate success or failure, and output parameters to return error messages.

Here’s how we might use this in a main function:

function ExecuteMain()
{
    local string ErrorMsg;
    local bool Success;

    Success = F(42, ErrorMsg);
    if (!Success)
    {
        `log("Error occurred: " $ ErrorMsg);
    }
    else
    {
        `log("Function executed successfully");
    }
}

In this example, we call the function F with the argument 42. If an error occurs (which it will in this case), the function returns false and populates the ErrorMsg string with our custom error message.

To run this code, you would typically include it in an actor or gameinfo class and call ExecuteMain() from an appropriate event like PostBeginPlay().

While UnrealScript doesn’t have an exact equivalent to Go’s errors.As(), this approach allows us to create and handle custom error types in a way that’s idiomatic to UnrealScript and the Unreal Engine environment.