Custom Errors in ActionScript

In ActionScript, we can create custom errors by extending the Error class. Here’s an example that demonstrates this concept:

package {
    import flash.display.Sprite;
    import flash.errors.IllegalOperationError;

    public class CustomErrors extends Sprite {
        public function CustomErrors() {
            // A custom error type usually has the suffix "Error".
            class ArgError extends Error {
                private var _arg:int;

                public function ArgError(arg:int, message:String) {
                    super(arg + " - " + message);
                    _arg = arg;
                }

                public function get arg():int {
                    return _arg;
                }
            }

            function f(arg:int):* {
                if (arg == 42) {
                    // Return our custom error.
                    throw new ArgError(arg, "can't work with it");
                }
                return arg + 3;
            }

            try {
                f(42);
            } catch (e:ArgError) {
                trace(e.arg);
                trace(e.message);
            } catch (e:Error) {
                trace("err doesn't match ArgError");
            }
        }
    }
}

In this example, we define a custom ArgError class that extends the built-in Error class. This custom error includes an arg property and a custom message.

The f function demonstrates how to throw this custom error when a specific condition is met (in this case, when the argument is 42).

In the try-catch block, we attempt to call f(42), which will throw our custom error. We then catch this error specifically as an ArgError and access its properties.

To run this code, you would typically compile it into a SWF file and run it in a Flash player or AIR runtime environment. The output would be:

42
42 - can't work with it

This approach allows for more detailed and specific error handling in ActionScript, similar to custom errors in other languages.

Note that ActionScript doesn’t have a direct equivalent to Go’s errors.As function. Instead, we use the catch clause with specific error types to handle different kinds of errors.