-
-
Save PatrickJS/8258632 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| /** | |
| * Implement a tryCatch() method that logs exceptions for method invocations AND | |
| * promise rejection activity. | |
| * | |
| * @param notifyFn Function callback with logging/exception information (typically $log.error ) | |
| * @param scope Object Receiver for the notifyFn invocation ( optional ) | |
| * | |
| * @return Function used to guard and invoke the targeted actionFn | |
| */ | |
| function makeTryCatch( notifyFn, scope ) | |
| { | |
| /** | |
| * Report error (with stack trace if possible) to the logger function | |
| */ | |
| var isObject = function (value) | |
| { | |
| return value != null && typeof value == 'object'; | |
| }, | |
| reportError = function (reason) | |
| { | |
| if(notifyFn != null) | |
| { | |
| var error = (reason && reason.stack) ? reason : null, | |
| message = reason != null ? String(reason) : ""; | |
| if(error != null) | |
| { | |
| message = error.message + "\n" + error.stack; | |
| } | |
| notifyFn.apply(scope, [message]); | |
| } | |
| return reason; | |
| }, | |
| /** | |
| * Publish the tryCatch() guard 'n report function | |
| */ | |
| tryCatch = function (actionFn, scope, args) | |
| { | |
| try | |
| { | |
| // Invoke the targeted `actionFn` | |
| var result = actionFn.apply(scope, args || []), | |
| promise = ( isObject(result) && result.then ) ? result : null; | |
| // Catch and report any promise rejection reason... | |
| if ( promise ) | |
| { | |
| promise.then( null, reportError ); | |
| } | |
| actionFn = null; | |
| return result; | |
| } | |
| catch(e) | |
| { | |
| actionFn = null; | |
| throw reportError(e); | |
| } | |
| }; | |
| return tryCatch; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment