In my app.module().run(), I set an onerror message to pop a toastr message whenever a javascript error is encountered.
I would like this to work across my entire ngApp. Is that possible?
The following code pops a toast because asdf is invalid JavaScript.
angular.module("app").run(['notificationFactory', '$window',
function (notificationFactory, $window) {
$window.onerror = function (errorMsg, url, lineNumber) {
notificationFactory.error(errorMsg);
};
asdf
}]);
But if I put 'asdf' into a controller, $window.onerror doesn't fire.
Is it possible to catch this with a global onerror call?
App.run is in my app.js file, and loads before my controllers.
Within my controller, I can't seem to get $window.onerror to work at all. I tried moving the onerror function to the controller. I also tried to see if an img tag would generate the error to no avail.
<img ng-src="someFileThatDoesntExist.png" />
You can decorate $exceptionHandler provider. Try below;
(function () {
'use strict';
var app = angular.module('myApp');
// Configure by setting an optional string value for appErrorPrefix.
// Accessible via config.appErrorPrefix ().
app.config(['$provide', function ($provide) {
$provide.decorator('$exceptionHandler',
['$delegate', 'notificationFactory', extendExceptionHandler]);
}]);
// Extend the $exceptionHandler service to also display a toast.
function extendExceptionHandler($delegate, notificationFactory) {
var appErrorPrefix = 'myPrefix';
return function (exception, cause) {
$delegate(exception, cause);
if (appErrorPrefix && exception.message.indexOf(appErrorPrefix) === 0) { return; }
var errorData = { exception: exception, cause: cause };
var msg = appErrorPrefix + exception.message;
notificationFactory.error(msg);
console.log(appErrorPrefix, errorData)
};
}
})();
The window.onerror event will not fire from a console error. Here's how you can fire the window.onerror event manually from console:
setTimeout(function() { notThere(); }, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With