Skip to content

Instantly share code, notes, and snippets.

@ThomasBurleson
Last active December 28, 2015 12:29
Show Gist options
  • Save ThomasBurleson/ae7bf135b44bae58d3a5 to your computer and use it in GitHub Desktop.
Save ThomasBurleson/ae7bf135b44bae58d3a5 to your computer and use it in GitHub Desktop.
Demonstrate how to guard targeted functions invocations using a `super` version of try-catch: The guard will report exceptions (with stack traces) via the logger function. If the target function returns a promise, then a rejection handler is attached; which will also report rejections and possible stack traces.
/**
* @param notifyFn Function used to log.debug exception information
* @param scope Object Receiver for the notifyFn invocation
*
* @return Function used to guard and invoke the targeted actionFn
*/
public function makeTryCatch( receiver:Object, notifyFn:Function = null ) : Function
{
// Lookup a default logger function if not specified
notifyFn ||= receiver[ "debug" ] as Function;
/**
* Report error (with stack trace if possible) to the logger function
*/
function reportError( reason : * ) : *
{
if ( notifyFn != null)
{
var message : String = String( reason );
var error : Error = reason as Error;
if ( error != null )
{
message = error.message + "\n" + error.getStackTrace();
}
notifyFn.apply( receiver, [ message ] );
}
return reason;
}
/**
* Publish the tryCatch() guard 'n report function
*/
return function tryCatch( actionFn : Function, scope:Object=null ) : *
{
try
{
// Invoke the targeted `actionFn`
var result : * = actionFn.apply( scope );
var promise : Promise = result as Promise;
if ( promise != null )
{
// Catch and report any promise rejection reason...
promise.otherwise( reportError );
}
actionFn = null;
return result;
} catch ( e:Error ) {
actionFn = null;
reportError( e );
throw e;
}
};
}
@ThomasBurleson
Copy link
Author

var logger   = new Logger( "MyAsyncMusicService" );
var tryCatch = makeTryCatch( logger );

tryCatch( function( ):*
{
    return musicPlayer
            .play()
            .then( announceState( PlayStateEnum.PLAYING ) );
},this);

@ThomasBurleson
Copy link
Author

Please note, the above code presumes use of the AS3 Promises library

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment