Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to catch JavaScript errors within an Angular app from $window.onerror

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" />
like image 433
Hoppe Avatar asked Jan 05 '15 15:01

Hoppe


2 Answers

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)
    };
}
})();
like image 162
Mehmet Otkun Avatar answered Nov 14 '22 23:11

Mehmet Otkun


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);
like image 26
michaeljiz Avatar answered Nov 14 '22 23:11

michaeljiz