Search code examples
actionscript-3ioactionscripthttp-get

How to catch Stream Error in ActionScript


I have the following piece of code, which attempts to GET a publicly hosted (AWS S3) file.

private function ShowS3Message():void
{
    // Attempt to download file from AWS
    var descriptor:XML = NativeApplication.nativeApplication.applicationDescriptor;
    var ns:Namespace = descriptor.namespaceDeclarations()[0];
    var url:String = "https://s3.amazonaws.com/some-url/file-" + descriptor.ns::versionLabel.split(".").join("-") + ".txt";
    var urlRequest:URLRequest = new URLRequest(url);

    // Set up callback function
    try{
        var loader:URLLoader = new URLLoader(); 
        loader.addEventListener(Event.COMPLETE, awsFetchCallback);                      
        loader.load(urlRequest);
    }catch(error:Error){}   
}

This is the callback function:

/**
 * Callback function for AWS message file
 */
private function awsFetchCallback(event:Event):void
{
    var data = event.target.data;

    // show dialog
    var msb:InformationMessageBox = new InformationMessageBox();
    msb.mText = data;
    msb.open(this, true);
}

When the file exists, there is no problem, and the code runs fine. When the file doesn't exist, this throws a StreamError, despite the catch block.

what am I missing?


Solution

  • You should capture the IO error event, there is not exception thrown when the file does not exist.

    loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);

    and then create your own error handler function.

    more details in the doc here : https://help.adobe.com/fr_FR/FlashPlatform/reference/actionscript/3/flash/net/URLLoader.html

    If you just want to drown the error (because you seem to know the file may not exist sometimes) it is sufficient to create an empty error event handler.