-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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; | |
} | |
}; | |
} |
Author
ThomasBurleson
commented
Nov 16, 2013
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