Category: ActionScript

  • Exception Handling in ActionScript 3 for AdBlock Plus

    I was reading Coldfused about AdBlock Plus, a Firefox plug-in that blocks ads and other elements of websites while you surf. I remembered that since upgrading to Firefox 2.0.0.11, my regular AdBlock plug-in is apparently not compatible. AdBlock Plus is.

    Upon installing and giving her a run, I noticed a video player application I’m writing for work started throwing an exception I hadn’t seen before. We’re using Dart for Publishers via a proxy company for one particular project, which still requires a URL request on the client to DoubleClick’s ad servers, ad.doubleclick.net, with 50 billion parameters on the URL. DoubleClick’s one of the biggest ad services on the net, one of the reasons Google bought ’em I’m sure. Therefore, they are also one of the filters that AdBlock Plus looks for and actively blocks. Any calls to doublelclick anything fail since it’s stopped at the browser level.

    This causes an IOError for URLLoader’s in ActionScript 3. I reckon this’ll throw a FaultEvent for HTTPService in Flex, but if you’re doing boiler-plate coding in either ActionScript only projects or Flash CS3 using URLLoader, you’ll need to write code to handle this in case any of your clients have ad blocking software installed. We already have a lot of exception handling on our own stuff since we develop on development & QA servers first and things can get wonky when the server guys update their stuff and something goes awry… or our client code is coded wrong. The only error’s we had seen in the Ad stuff was when the DoubleClick servers were configured wrong at a client site, and you’d get back a 1 pixel by 1 pixel transparent GIF in HTML instead of the XML you were expecting. In that case, we’d just dispatch a custom error event in the parsing function. This rarely happened and our error code was sound.

    …so I thought until I installed AdBlock Plus and re-tested our app. For the record, you should be doing at least this level of exception handling, if not more if you are doing any coding with classes that throw errors. In AS2 it was ok if things blew up; no one knew. Not the user, nor you. In AS3, however, the recovery isn’t always as good; a lot of times the code will just abort the whole stack. Since you can’t do this code on _root:

    try
    {
            runSWF();
    }
    catch(err:Error)
    {
            // something somewhere blew up good in my appz0r
            showErrorScreenMovieClip();
    }

    You need catch everything possible if you want to ensure your code has any hope of continuing. The whole point of exceptions, according to Java developers, is to catch the exception, and handle as best you can. Obviously, a lot of exceptions leave you with no options. If you own the code, you can show an error screen, and if your code is going into something else, you can dispatch an error event. That’s about it for some exceptions.

    For those creating applications that need to show ads inside their Flash & Flex apps, you need to assume you’re entering a hostile landscape where people are going to do everything they can to block your ads. If your policy is that ads drive the revenue of your business, you can abort everything when an exception is thrown. If your policy is to not trust 3rd party servers that cost 5 figures but don’t even allow you to do a test movie in the Flash IDE, then you log the error, and just dispatch an error so the rest of your code can move on with life.

    Below is some pseudo code that shows how you write near exception-proof code that hits some URL. The only thing missing is a timeout error. Writing a timer is complicated and controversial, so I’ll skip that part and assume if you get a timeout, you destroy the URLLoader, remove the listeners, and just dispatch a custom error indicating a timeout.

    // create our loader
    adLoader = new URLLoader();
    adLoader.addEventListener(Event.COMPLETE, onLoaded);
    adLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    adLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);req = new URLRequest("ad.doubleclick.net/coldcrazyparams");
    
    // attempt to load
    try
    {
            adLoader.load(req);
    }
    catch(err:Error)
    {
            // Either HTTP Sniffer like Charles is running,
            // your VPN is offline, or your interwebs are silly.
            dispatchEvent(new Event("adError"));
    }
    
    // The host is ad-blocked or cannot be reached.
    protected function onIOError(event:IOErrorEvent):void
    {
            dispatchEvent(new Event("adError"));
    }
    
    // OT OT OT
    protected function onSecurityError(event:SecurityErrorEvent):void
    {
            dispatchEvent(new Event("adError"));
    }
    
    protected function onLoaded(event:Event):void
    {
            // all is well in the land of Hannah frikin' Lee
            // show ads, make bling, drink & celebrate
    }

    Don’t forget to put [Event] metadata tags at the top, so all people using your class (including you) get code hints in FlexBuilder for addEventListener. Usually, there should be at least 2 events in my opinion; complete and error. Since we don’t have throwable like Java, exceptions break the heck out of encapsulation, and events are both synchronous and asynchronous; events for the win.

    Side Rant

    Unfortunately, what the code above can’t do is dodge the dreaded VerifyError, aka invalid register accessed etc etc. You get this if your SWF gets corrupted in some way. I got one of these with Flex Builder 3 Beta 2. At first, I tracked it down do a nested XML namespace. Later, it turned out there was “magic funk” around the error function itself I routed exceptions to. I noticed that older CSS files had all of these errors for every style from a Flex 2 project. If I re-wrote them the exact same, letter for letter, they were fine. So, copied and pasted the whole thing to Notepad, and then back… and everything was fine. WTF? UTF-8 demon infestation? Anyway, tried same theory here; re-wrote function a good 5 blank lines away and low and behold, no more VerifyError. I’m hoping it was just a Beta 2 problem.

    Anyway, Flex Builder 3 Beta 3 rules so far.

  • Mix n Mash 2k7, Bill Gates, Web, Blend, and Silverlight

    I had the honor of being 1 of the lucky 10 invited to attend the Mix n Mash 2007 event held by Microsoft. This is the 2nd one. It’s an event where they invite you to Microsoft’s HQ to see what they are working on, give feedback, and meet Bill Gates.

    Here’s a picture of the Mix n Mash invited attendee’s getting their picture taken with Bill Gates (I somehow got in there, booya!)

    From left to right:

    Jonathan Snook, Julie Lerman, Kelly Goto, Rob Howard, Bill Gates, Molly Holzschlag, Kip Kniskern, Jesse Warden (me!), Keith Peters and Erik Natzke

    (more…)

  • Your Mom is null throws Exception OT OT OT … or Learning Exception Handling in ActionScript

    After coding AS3 for about 2 years now, I’ve come to 1 conclusion: I’m sick and tired of testing for null. It seems to be the most common if then statement I write in all of my code. I’ve been doing some pure ActionScript work in the past few months, and I have to so say, the more ActionScript only, as opposed to Flex projects using MXML, code I write has more of these checks. It’s nice how MXML handles all the deferred instantiation stuff for you. I certainly have more appreciation for it. Same with Flash CS3 and automatically declaring stage instances.

    The second reason, however, is exceptions. I’ve never had to use exceptions until now. Half the reason is 90% of all exceptions in Flex are bugs that you can fix in your code. When doing API work, it’s the opposite. I cannot control what gets passed into my code when I plug libraries into some other project. I have the benefit of drinking my own kool-aid; we’re using the very API’s we create. There came a point last week where I realized that some of the exceptions weren’t my fault. Meaning, I could go to a court of law, represent myself, and still win with utter confidence. When developers use an API, you cannot control what they put into it. While you can expose some strongly typed public methods, and hope for the best, but ultimately they’re going to pass something in there that is null, NaN, or just plain wrong.

    For debugging, it’s easy; you can use default values when you don’t have time to correct the one who is using the API if you are coding both yourself. You can’t do that, though, in production. When creating video players for work, if I have 2 million customers having SWF’s on their desktop trying to hit our internal development server that cannot be reached without VPN… that’s a bad thing.

    Running into that scenario, I started trying to handle some of the exceptions myself. I started to get some deeply nested try/catch blocks. The code started to look really nasty (maybe ’cause I’m not used to it). However, I started feeling really confident that if something didn’t work, I can could capture it in one place, and create an error screen for it. After awhile, this spiraled out of control. Suddenly, I was catching just about every method. In short, it’s bs; I shouldn’t have to code like that. Clearly I was in uncharted territory that the C++ and Java crowd had already figured out.

    Whilst the bird was cooking, I went digging on Google and found 2 good articles (Best Practices for Exception Handling, Exceptions in Java: Nothing Exceptional About Them). I told her majesty I wouldn’t work over the holidays; I don’t count learning exception handling as working. The one on Sun’s site I didn’t agree with. Furthermore, while the articles are years old, and appear to disquiet controversy, it sounds like the same arguments Flash Developers have of code on frames vs. no code on frames. Both are valid, 1 is a purist angle, the other a pragmatic angle. Doing my best with just 3 hours worth of research, it seems that Java has checked and unchecked exceptions; in the Flash Player world meaning those that show the debugger popup window in the debug player, and those that do not. I’ve yet to see an exception not show a debug window. I had 1 nestled deeply in a View not do it once, but I think that was a bug in the beta Flex 3 bits I’m using. So… it doesn’t sound like ActionScript has an unchecked exception equivalent.

    That said, if you read Sun’s article explaining the reasoning behind unchecked exceptions, they justify it by saying there are just some errors you either can’t reasonably recover from, and there are too many exceptions to possibly catch. If you did, you’re code would become too verbose and un-readable.

    I call busllshit. First off, YOU MUST recover. If you’re a GUI developer like me, you know that you can’t show user’s a cryptic error screen, or worse, nothing. Heck, if you’ve ever used Windows and got some useless error screen with no information on how to proceed, all it did was make you frustrated with no clue on how to solve your problem… nor even a clue as to what the problem even is. Unfortunately, this is a problem in the Flash Player as well; there is no way to catch all exceptions assuming you put a big-ole try catch on _root for example. Even though exceptions can act like events for asynchronous exceptions (aka, Error’s that have an Event equivalent are dispatched when something goes wrong, and you ‘catch’ them like you do events via addEventLsitener ). You can’t do that, but that’s what a lot of us want for Enterprise apps, or those apps that CANNOT have errors thrown under any circumstance in production code. I’d still argue, however, that most of the relevant ones you can catch and handle. There is a caveat to this I’ll mention later.

    Secondly, after reading the 2 other articles, you are not pre-disposed to write bad code proportional to the amount of exceptions thrown. This is a fallacy Java’s designers apparently thought would happen… maybe they didn’t want to have their uber-sexy OOP language look like Eiffel, no clue. Bottom line is, there are good ways to throw and handle exceptions in Java, C++, and ActionScript.

    After reading the articles, one mentioned the anti-pattern of deeply nested try / catch blocks. I’d only be doing exception handling for 2 days, and already I used an anti-pattern… sweet, I suck! In doing so, I clearly recognize the key point in one of the articles; exceptions can break encapsulation. The consumer of the API had to know too much about the API to use it; meaning, it had to know what could go wrong with it and handle it. Shouldn’t an API handle it’s own problems or at least lessen the amount of code I have to write? Isn’t that the point of an API? When I started seeing my code checking for IOError’s on URLLoader, which my code shouldn’t even know a URLLoader is being used, I clearly saw the break in encapsulation. It’s a bad feeling to not know if you are doing something correctly. It’s great, however, to know you are clearly doing something utterly wrong. That means there is a RIGHT way to do it. Google search FTW!

    Java has this thing called throws; it’s a keyword that goes on the end of a function in Java, and forces the method that calls it to use a try catch block just in case the method does throw an error. It’s nice because it’s a compiler thing, so the code won’t even compile unless you use the method correctly. This is problematic in ActionScript for 2 reasons. First, ActionScript doesn’t block so you can’t do a try / catch on an asynchronous method. Secondly, there is no “throws” equivalent for events; since Error’s are treated as events and dispatched the same way, you cannot force someone to use an addEventListener in ActionScript. Even if you could, you cannot control how they do so. For example, if you used a weak listener to an addEventListener, and there were no hard references to it, so Garbage Collection ate it, the exception wouldn’t be “caught” by an event listener. Technically you made the compiler happy, but you failed to catch said exception/event.

    The point here is in Java this is part of the language, the contract that goes along with strong-typing. While interfaces are a programming by contract methodology, so to are throws in Java. It seems to me this is not a strong point of ActionScript (at least the parts ofECMA 4 it’s implanted; haven’t read where ECMA 4 is going), nor are there any best practices yet since the API creation field for ActionScript has just now started on a major up-swing (don’t believe Zoho, they’re full of it, there are a lot of great AS3 libraries. Do a google search).

    To Sun’s credit, in reading the 2 articles, I didn’t realize one particular scenario, and that is if your API is put into a GUI you don’t have control over. It’s really easy for me to think, “Sure, if there is an error, I’ll just have my designer create an error screen for it, or have some Information Architect / Interaction Designer document which exceptions do what in the interface”. That’s all well and good if you are the one both creating and consuming the API. For some of our customers, that is a set of glorious, and wrong, assumptions. First off, they shouldn’t have to know about our API too much to use it. For all the crap I give f’ing DoubleClick , their API is brain-dead simple to use. They still suck that they don’t support AS3, though. Second, I cannot control customers’ GUI; if they choose not to show an error screen because something didn’t load properly, who’s fault is that… mine or theirs? It’s mine if I didn’t provide an easy, simplified way of letting them know when something went wrong. Only then is it theirs. Third, error handling is yet ANOTHER thing to do. Thus, it takes time. A lot of Flash work sometimes is under insane deadlines; just because I have reasonable deadlines with reasonable management and competent developers does not mean that our customers will be as lucky. I need to work extra hard to make sure I make their job as easy as possible. Aka, a good API.

    In short, what I gleaned is:

    1. Don’t ignore exceptions. Find out why your code is breaking and fix it. For those situations which you can’t control, handle it, clean up your mess, and dispatch/throw an error.
    2. Don’t over architect your Error’s. Some internal error’s are perfectly named; use them instead of your own. The RangeError is a good example. If you try to access item 10 of an array that only has 9 items, you don’t need to abstract that further, nor shield an API user from it. It’s a simple error that comes from using array’s.
    3. Going along with point #1, if you have a ton of errors that could potentially happen, consolidate them so users of your API only get 1 error (or is few as possible). You do this by extending Error and then throwing / dispatching it. If they really want to know the root cause, store the original error as a class member.

    Again, if you are creating a Flex app, you probably don’t have to worry about this too much. I’d argue most exceptions are something you did, in your code. A lot of us Flash Developers have the perception of exceptions as being “errors in your code”. Our attitude typically is, “If there is a bug in your code… fix it.” This perception breaks down when you start creating API’s for others that you cannot control how they use it. That, or just the user’s internet connection goes down and an IOError is thrown. You can’t fix the interwebs connection using Flash.

    I’m sure how to resolve Joel’s angle. While I wasn’t much of a coder back then, handling “error codes” in Director’s Multiuser Server was a royal pain in the neck, so not sure how to code to what he’s suggesting. Painting by numbers is fun… coding by them is not.

  • Flash & Flex Integration Gotcha: Automatically Declare Stage Instances

    I’ve gotten a lot of emails asking about some of my older Flash & Flex integration examples not working. Hopefully this article will describe the same error everyone is getting.

    ActionScript 3 is strict. However, Flash CS3 helps Flash developers with a feature that automatically generates code during compilation. Meaning, if you have a MovieClip on the stage called “my_anime”, you won’t have to declare a variable like so:

    public var my_anime:MovieClip;

    Flash CS3 will automatically write that in the code for you.

    If you didn’t have that code, you’ll get a runtime exception. That’s because the timeline is effectively going:

    yourMovieClipInstance.my_anime = new MovieClip();
    yourMovieClipInstance.addChild(yourMovieClipInstance.my_anime);

    Since yourMovieClipInstance’s class doesn’t have a property called “my_anime”, it’ll blow up. For a Flex Developer, this makes sense. Everything exists, and you merely addChild/removeChild or toggle the visible property. In Flash, things may not exist till frame 10. For some animations that have a ton of child MovieClips that you need to talk to, this can be a lot to remember. So, the ADSI feature is nice in that Flash worries about it for you.

    Flex has no such feature.  When you bring in Flash content, you’ll get an exception, and you can’t debug it easily because it was the MovieClip’s timeline who caused the error. When you go to debug, you’ll get the 1 line exception “ReferenceError: Error #1056: Cannot create property” in the call stack, and nothing more… and you’re left wondering, who the heck is creating this thing?

    While I agree why Adobe put the ADSI feature in Flash CS3, it works against you when you create content for Flex. Take the pain of writing out all of your MovieClip’s as class member properties, and uncheck ADSI via:

    1. File > Publish Settings
    2. Flash tab
    3. Settings button
    4. un-check “Automatically declare stage instances”

    Good to go funky coma-deena.

    Here’s the settings screen:

    Settings Screen

    Here you can see a new animation starts on frame 25. Therefore, if there is no class variable called “box”, you’ll get a runtime exception. In Flash CS3, however, you won’t if you have ADSI checked.

    Timeline Animation Example

    Here, you can see I define the box on line 8; this prevents a runtime exception when you embed the SWF in Flex.

    Class Example