Example: CustomErrors application. Adobe Flex, FLEX 2-PROGRAMMING ACTIONSCRIPT 3.0
Below you will find brief information for ActionScript 3.0 Programming. This manual provides a foundation for developing applications in ActionScript 3.0, covering core concepts such as language syntax, object-oriented programming, and the Flash Player API. Learn about event handling, networking, and more to build robust and interactive applications.
Advertisement
Advertisement
flash.error package Error classes
The flash.error package contains Error classes that are considered part of the Flash Player API.
In contrast to the Error classes just described, the flash.error package communicates errors events that are specific to Flash Player.
Class name Description Notes
EOFError
IllegalOperationError An IllegalOperationError exception is thrown when a method is not implemented or the implementation doesn't cover the current usage.
Examples of illegal operation error exceptions include the following:
• A base class, such as
DisplayObjectContainer, provides more functionality than the Stage can support. For example, if you attempt to get or set a mask on the Stage (using stage.mask
),
Flash Player will throw an
IllegalOperationError with the message “The Stage class does not implement this property or method.”
• A subclass inherits a method it does not require and does not want to support.
• Certain accessibility methods are called when Flash Player is compiled without accessibility support.
• Authoring-only features are invoked from a run-time version of
Flash Player.
• You attempt to set the name of an object placed on the timeline.
IOError
An EOFError exception is thrown when you attempt to read past the end of the available data.
For example, an EOFError is thrown when one of the read methods in the
IDataInput interface is called and there is insufficient data to satisfy the read request.
An IOError exception is thrown when some type of I/O exception occurs.
You get this error, for example, when a read-write operation is attempted on a socket that is not connected or that has become disconnected.
Comparing the Error classes 275
Class name Description Notes
MemoryError A MemoryError exception is thrown when a memory allocation request fails.
By default, ActionScript Virtual
Machine 2 does not impose a limit on how much memory an
ActionScript program may allocate.
On a desktop PC, memory allocation failures are infrequent.
You see an error thrown when the system is unable to allocate the memory required for an operation.
So, on a desktop PC, this exception is rare unless an allocation request is extremely large; for example, a request for 3 billion bytes is impossible because a 32-bit
Windows program can access only
2 GB of address space.
ScriptTimeoutError A ScriptTimeoutError exception is thrown when a script timeout interval of 15 seconds is reached.
By catching a
ScriptTimeoutError exception, you can handle the script timeout more gracefully. If there is no exception handler, the uncaught exception handler will display a dialog box with an error message.
To prevent a malicious developer from catching the exception and staying in an infinite loop, only the first ScriptTimeoutError exception thrown in the course of a particular script can be caught. A subsequent
ScriptTimeoutError exception cannot be caught by your code and will immediately go to the uncaught exception handler.
StackOverflowError The StackOverflowError exception is thrown when the stack available to the script has been exhausted.
A StackOverflowError exception might indicate that infinite recursion has occurred.
276 Handling Errors
Example: CustomErrors application
The CustomErrors application demonstrates techniques for working with custom errors when building an application. These techniques are:
■
■
■
■
Validating an XML packet
Writing a custom error
Throwing custom errors
Notifying users when an error is thrown
The CustomErrors application files can be found in the Samples/CustomError folder. The application consists of the following files:
File
CustomErrors.mxml
com/example/programmingas3/errors/
ApplicationError.as
com/example/programmingas3/errors/
FatalError.as
com/example/programmingas3/errors/
Validator.as
com/example/programmingas3/errors/
WarningError.as
Description
The main application file consisting of the
MXML user interface.
A class that serves as the base error class for both the FatalError and WarningError classes.
A class that defines a FatalError error that can be thrown by the application. This class extends the custom ApplicationError class.
A class that defines a single method that validates a user-supplied employee XML packet.
A class that defines a WarningError error that can be thrown by the application. This class extends the custom ApplicationError class.
CustomErrors application overview
The CustomErrors.mxml file contains the user interface and some logic for the custom error application. Once the application’s creationComplete event is dispatched, the initApp() method is invoked. This method defines a sample XML packet that will be verified by the
Validator class. The following code shows the initApp() method: private function initApp():void
{ employeeXML =
<employee id="12345">
<firstName>John</firstName>
<lastName>Doe</lastName>
<costCenter>12345</costCenter>
<costCenter>67890</costCenter>
Example: CustomErrors application 277
</employee>;
}
The XML packet is later displayed in a TextArea component instance on the Stage. This allows you to modify the XML packet before attempting to revalidate it.
When the user clicks the Validate button, the validateData() method is called. This method validates the employee XML packet using the validateEmployeeXML() method in the Validator class. The following code shows the validateData() method: public function validateData():void
{ try
{ var tempXML:XML = XML(xmlText.text);
} catch (error:FatalError)
{
Validator.validateEmployeeXML(tempXML); status.text = "The XML was successfully validated."; showFatalError(error);
} catch (error:WarningError)
{ showWarningError(error);
} catch (error:Error)
{ showGenericError(error);
}
}
First, a temporary XML object is created using the contents of the TextArea component instance xmlText . Next, the validateEmployeeXML() method in the custom Validator class
(com.example.programmingas3/errors/Validator.as) is invoked and passes the temporary
XML object as a parameter. If the XML packet is valid, the status Label component instance displays a success message and the application exits. If the validateEmployeeXML() method threw a custom error (that is, a FatalError, WarningError, or a generic Error occurred), the appropriate catch statement executes and calls either the showFatalError() , showWarningError() , or showGenericError() methods. Each of these methods displays an appropriate message in an Alert component to notify the user of the specific error that occurred. Each method also updates the status Label component instance with a specific message.
278 Handling Errors
If a fatal error occurs during an attempt to validate the employee XML packet, the error message is displayed in an Alert component, and the xmlText TextArea component instance and validateBtn Button component instance are disabled, as the following code shows: public function showFatalError(error:FatalError):void
{ var message:String = error.message + "\n\n" + "Click OK to end."; var title:String = error.getTitle();
Alert.show(message, title); status.text = "This application has ended."; this.xmlText.enabled = false; this.validateBtn.enabled = false;
}
If a warning error instead of a fatal error occurs, the error message is displayed in an Alert component instance, but the TextField and Button component instances aren’t disabled. The showWarningError() method displays the custom error message in the Alert component instance. The message also asks the user to decide if they want to proceed with validating the
XML or abort the script. The following excerpt shows the showWarningError() method: public function showWarningError(error:WarningError):void
{ var message:String = error.message + "\n\n" + "Do you want to exit this application?"; var title:String = error.getTitle();
Alert.show(message, title, Alert.YES | Alert.NO, null, closeHandler); status.text = message;
}
When the user closes the Alert component instance by using either the Yes or No button, the closeHandler() method is invoked. The following excerpt shows the closeHandler() method: private function closeHandler(event:CloseEvent):void
{ switch (event.detail)
{ case Alert.YES: showFatalError(new FatalError(9999)); break; case Alert.NO: break;
}
}
If the user chooses to abort the script by clicking Yes in the warning error Alert dialog, a
FatalError is thrown, causing the application to terminate.
Example: CustomErrors application 279
Building a custom validator
The custom Validator class contains a single method, validateEmployeeXML() . The validateEmployeeXML() method takes a single argument, employee , which is the XML packet that you wish to validate. The validateEmployeeXML() method is as follows: public static function validateEmployeeXML(employee:XML):void
{
// checks for the integrity of items in the XML if (employee.costCenter.length() < 1)
{ throw new FatalError(9000);
} if (employee.costCenter.length() > 1)
{ throw new WarningError(9001);
} if (employee.ssn.length() != 1)
{ throw new FatalError(9002);
}
}
To be validated, an employee must belong to one (and only one) cost center. If the employee doesn’t belong to any cost centers, the method throws a FatalError, which bubbles up to the validateData() method in the main application file. If the employee belongs to more than one cost center, a WarningError is thrown. The final check in the XML validator is that the user has exactly one social security number defined (the ssn node in the XML packet). If there is not exactly one ssn node, a FatalError error is thrown.
You can add additional checks to the validateEmployeeXML() method—for instance, to ensure that the ssn node contains a valid number, or that the employee has at least one phone number and e-mail address defined, and that both values are valid. You can also modify the
XML so that each employee has a unique ID and specifies the ID of their manager.
Defining the ApplicationError class
The ApplicationError class serves as the base class for both the FatalError and WarningError classes. The ApplicationError class extends the Error class, and defines its own custom methods and properties, including defining an error ID, severity, and an XML object that contains the custom error codes and messages. This class also defines two static constants that are used to define the severity of each error type.
280 Handling Errors
The ApplicationError class’s constructor method is as follows: public function ApplicationError()
{ messages =
<errors>
<error code="9000">
<![CDATA[Employee must be assigned to a cost center.]]>
</error>
<error code="9001">
<![CDATA[Employee must be assigned to only one cost center.]]>
</error>
<error code="9002">
<![CDATA[Employee must have one and only one SSN.]]>
</error>
<error code="9999">
<![CDATA[The application has been stopped.]]>
</error>
</errors>;
}
Each error node in the XML object contains a unique numeric code and an error message.
Error messages can be easily looked up by their error code using E4X, as seen in the following getMessageText() method: public function getMessageText(id:int):String
{ var message:XMLList = messages.error.(@code == id); return message[0].text();
}
The getMessageText() method takes a single integer argument, id , and returns a string.
The id argument is the error code for the error to look up. For example, passing an id of
9001 retrieves the error saying that employees must be assigned to only one cost center. If more than one error has the same error code, ActionScript returns the error message only for the first result found ( message[0] in the returned XMLList object).
The next method in this class, getTitle() , doesn’t take any parameters and returns a string value that contains the error ID for this specific error. This value is used in the Alert component’s title to help you easily identify the exact error that occurred during validation of the XML packet. The following excerpt shows the getTitle() method: public function getTitle():String
{ return "Error #" + id;
}
Example: CustomErrors application 281
The final method in the ApplicationError class is toString(). This method overrides the function defined in the Error class so that you can customize the presentation of the error message. The method returns a string that identifies the specific error number and message that occurred.
public override function toString():String
{ return "[APPLICATION ERROR #" + id + "] " + message;
}
Defining the FatalError class
The FatalError class extends the custom ApplicationError class and defines three methods: the
FatalError constructor, getTitle() , and toString() . The first method, the FatalError constructor, takes a single integer argument, errorID , and sets the error’s severity using the static constant values defined in the ApplicationError class, and gets the specific error’s error message by calling the getMessageText() method in the ApplicationError class. The
FatalError constructor is as follows: public function FatalError(errorID:int)
{ id = errorID; severity = ApplicationError.FATAL; message = getMessageText(errorID);
}
The next method in the FatalError class, getTitle() , overrides the getTitle() method defined earlier in the ApplicationError class, and appends the text “-- FATAL” in the title to inform the user that a fatal error has occurred. The getTitle() method is as follows: public override function getTitle():String
{ return "Error #" + id + " -- FATAL";
}
The final method in this class, toString() , overrides the toString() method defined in the
ApplicationError class. The toString() method is public override function toString():String
{ return "[FATAL ERROR #" + id + "] " + message;
}
282 Handling Errors
Download
Advertisement
Key features
Comprehensive guide to ActionScript 3.0
Covers core language features and Flash Player APIs
Numerous code examples and sample applications
Explains object-oriented programming concepts
Detailed explanation of event handling and networking
Frequently asked questions
ActionScript 3.0 offers performance improvements (up to ten times faster), a more robust programming model, an improved API, and features like E4X for XML manipulation and native regular expressions.
ActionScript 3.0 uses run-time exceptions to report errors, providing stack traces for easier debugging and enabling robust error handling in applications.
The API includes classes like Sprite and Shape for working with visual elements, providing more control and dynamic re-parenting capabilities. Depth management is automatic.
ActionScript 3.0 uses ECMAScript for XML (E4X), making XML manipulation more intuitive and efficient through native language constructs.