With FlashPlayer 10.1 comes the ability to handle all the exceptions at one place, aka, Global Error Handler. This means a SWF can be made so that it does not pop-up usual error message dialogues, we generally see now a days with a lot many sites, if we have a debug version of the player. This simply does not mean we should ignore any errors in code. What does it mean is, we still have another gate to filter out any error messages from our application. There can be situation in a team environment, where someone can missout something and that will throw an error on runtime. Well, without further digging into the cause, lets dig into our point of handling the errors.
There is basically another property now to the “LoaderInfo” and “Loader” object. This property is known as “uncaughtErrorEvents”. The trick is to listen to “UncaughtErrorEvent.UNCAUGHT_ERROR” event on this property of the “LoaderInfo” and “Loader” object and handle it. Further more, if we completely want to supress the error dialogue box from poping out, “preventDefault()” must be called on the error handler.
Jumping to the code, add an event handler to the keyboard event like
On its handler try to remove a sprite from the display list,which is not yet present in the display list. The code is as below
private function onKeyDown(e:KeyboardEvent):void
var sp:Sprite = new Sprite();
At this point, if we try and run our swf and press any key on our keyboard, the error dialogue will come up.(Keep in mind, this only happens if we have a debug version of the FlashPlayer)
Well, now this dialogue is very annoying if we are an user. We can avoid this by handing the error on our GlobalError handler. In the beginning of the application listen for error on the LoderInfo object of the main application.
Now, on its handler call “preventDefault()” method of the error event.
private function handleGlobalErrors(e:UncaughtErrorEvent):void
//this suppresses the error dialogue
//application specific error handlers goes below
The full source code is available here. This is a full application setting in FlashDevelop. So one can directly open the application in FlashDevelop else just open the “Main.as” and compile it.
The next scenario is when we will be loading external SWFs into our main application. In this case just listen to the Loader objects “uncaughtErrorEvents” property for “UncaughtErrorEvent.UNCAUGHT_ERROR” event as below
var l:Loader = new Loader();
Thats all, now we have a Global Error Handler in place.
1. SWFs made for AVM1 with AS2 or AS1 can not be handled for errors on Global Error handler.
2. Even if the Error is handled in the Global Error Handler, the execution of the script does not continue on the call stack that caused the error.
Happy Flashing :)