Global Error Handling in Flex

12:28 pm in SOA Solutions by admin

I have worked on a few large Flex applications, and almost everything about the platform delights me — it is quick to prototype, powerful in creating rich UIs.  But it often frustrates me how difficult it is to handle run-time errors.  As the application scales, it becomes harder and harder to ensure that it will never emit a run-time error, and the default Flash Player behavior of freezing and not providing any user feedback will not cut the mustard. The approach I have found to work best is as follows (until a future beta of Flash Player 10 supports this out of the box). Jörg Birkhold describes how to tell the call later dispatcher to throw an event any time an error is thrown.


private function onPreinitialize():void {
  // setup global error handling
  UIComponentGlobals.catchCallLaterExceptions = true;
  systemManager.addEventListener("callLaterError", handleErrors);
}

I add an event handler in my Main application, doing the following:

  • Print the stack trace to the console for debugging, since it will no longer print by default
  • Pop an alert up to the user. Depending on how the error is thrown, this may or may not make it to the screen, but it will ensure the screen glosses over to prevent any further interaction.
  • If JavaScript is available, call a JavaScript function.  You can do anything you want here, but my preference is to redirect the user to an error page that tells them something went wrong, and links them to the correct page to restart where they left off.

public function handleErrors(event:Event):void {
  if (event is DynamicEvent && event.hasOwnProperty("error")) {
    // you could also send this back to your server
    var error:Error = DynamicEvent(event).error as Error;
    trace("Error!\n" + error.getStackTrace());
    Alert.show("There has been an error in the application", "", Alert.OK);

    if (ExternalInterface.available) {
      ExternalInterface.call("handleApplicationError");
    }
  }
}

Download the full demo