Global Error Handling in AIR 2.0 and Flash 10.1

One of the most popular feature announcements during my MAX presentation was global error handling (GEH). GEH lets you handle all uncaught errors (both synchronous errors and asynchronous error events) in one place in your code. Here’s an example of how it will work:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" applicationComplete="onApplicationComplete();">

<mx:Script>
<![CDATA[
private function onApplicationComplete():void
{
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, onUncaughtError);
}

private function onUncaughtError(e:UncaughtErrorEvent):void
{
// Do something with your error.
if (e.error is Error)
{
var error:Error = e.error as Error;
trace(error.errorID, error.name, error.message);
}
else
{
var errorEvent:ErrorEvent = e.error as ErrorEvent;
trace(errorEvent.errorID);
}
}

private function onCauseError(e:MouseEvent):void
{
var foo:String = null;
try
{
trace(foo.length);
}
catch (e:TypeError)
{
trace("This error is caught.");
}

// Since this error isn't caught, it will cause the global error handler to fire.
trace(foo.length);
}
]]>
</mx:Script>

<mx:Button label="Cause TypeError" click="onCauseError(event);"/>

</mx:WindowedApplication>

Registering for uncaught errors is hugely convenient, but it doesn’t entirely excuse developers from handling errors where they’re most likely to happen. For instance, you should still always register for things like IOError events and other errors that are likely to happen at some point, and that you can usually recover from. But starting with AIR 2.0 (and FP 10.1), you will also be able to register globally for errors that you weren’t able to anticipate, and handle them at least somewhat gracefully.

The big question is what you do once you’ve caught an unhandled error. That will probably depend on the application. Since it’s likely that a function exited without executing all the way through, there’s no telling what state your app will be in. The safest thing to do is probably to log the error, show a very contrite dialog box, and then exit the app (after all, if the error had been predictable and easy to recover from, you should have caught it explicitly). You might try sending the error message to your server, including instructions for emailing the log file to a support email address, or if it’s an internal application, provide a telephone extension to call for someone to come take a look. It’s entirely up to you. We provide the API, you provide the solution.