Adobe Flex 3 Help

Writing an error handler function

The protocol for formatters when detecting an error is to return an empty string, and to write a string describing the error condition to the error property of the formatter. You can check for an empty string in the return value of the format() method, and if found, access the error property to determine the cause of the error.

Alternatively, you can write an error handler function that returns an error message for a formatting error. The following example shows a simple error handler function:

<?xml version="1.0"?>
<!-- formatters\FormatterSimpleErrorForDevApps.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

    <mx:Script>
        <![CDATA[

            private function formatWithError(value:Object):String {
                var formatted:String = myFormatter.format(value);
                if (formatted == "") {
                    if (myFormatter.error != null ) {
                        if (myFormatter.error == "Invalid value") {
                            formatted = ": The value is not valid.";
                        }
                        else {
                            formatted = ": The formatString is not valid.";
                        }
                    }
                }
                return formatted;
            }
        ]]>
    </mx:Script>

    <!-- Declare a formatter and specify formatting properties.-->
    <mx:DateFormatter id="myFormatter" 
        formatString="MXXXMXMXMXMXM"/>

    <!-- Trigger the formatter while populating a string with data.-->
    <mx:TextInput id="myTI"
        width="75%"
        text="Your order shipped on {formatWithError('May 23, 2005')}"/> 
</mx:Application>

The executing SWF file for the previous example is shown below:

In this example, you define a DateFormatter with an invalid format string. You then use the formatWithError() method to invoke the formatter in the TextInput control, rather than calling the Date formatter's format() method directly. In this example, if either the input string or the format string is invalid, the formatWithError() method returns an error message instead of a formatted String value.