Errors in AngelScript

In AngelScript, error handling is typically done using exceptions, which is different from the explicit error return values used in some other languages. However, we can simulate a similar approach using return values. Here’s how we might implement the error handling example:

string f(int arg)
{
    if (arg == 42)
    {
        // Return an error message
        return "can't work with 42";
    }
    
    // Return a success message
    return "success: " + (arg + 3);
}

// Sentinel errors
const string ErrOutOfTea = "no more tea available";
const string ErrPower = "can't boil water";

string makeTea(int arg)
{
    if (arg == 2)
    {
        return ErrOutOfTea;
    }
    else if (arg == 4)
    {
        // Wrap the error
        return "making tea: " + ErrPower;
    }
    return ""; // No error
}

void main()
{
    array<int> nums = {7, 42};
    for (uint i = 0; i < nums.length(); i++)
    {
        string result = f(nums[i]);
        if (result.substr(0, 7) == "success")
        {
            print("f worked: " + result + "\n");
        }
        else
        {
            print("f failed: " + result + "\n");
        }
    }

    for (int i = 0; i < 5; i++)
    {
        string err = makeTea(i);
        if (err != "")
        {
            if (err == ErrOutOfTea)
            {
                print("We should buy new tea!\n");
            }
            else if (err.findFirst(ErrPower) != -1)
            {
                print("Now it is dark.\n");
            }
            else
            {
                print("unknown error: " + err + "\n");
            }
            continue;
        }
        print("Tea is ready!\n");
    }
}

In this AngelScript version:

  1. We use strings to represent errors instead of a separate error type.

  2. The f function returns a string that either starts with “success” or contains an error message.

  3. We define sentinel errors as constant strings.

  4. The makeTea function returns an empty string for success or an error message for failure.

  5. In the main function, we check for errors by examining the returned strings.

  6. We simulate error wrapping by concatenating strings.

  7. Instead of errors.Is, we use string comparison or findFirst to check for specific errors.

This approach mimics the error handling style of explicitly returning and checking for errors, adapted to AngelScript’s capabilities. It’s worth noting that in real AngelScript applications, using exceptions for error handling might be more idiomatic.

To run this script, you would typically use an AngelScript interpreter or embed it in a host application that supports AngelScript.