Amit
Amit

Reputation: 6294

Handling JavaScript errors with window.onerror

I am trying to handle my errors, but unfortunately I don't succeed.

In my AngularJS App 'run' I write this code:

window.onerror = function (msg, url, line, col, error) {
    alert('error');
};
$timeout(() => errorrr);

And while I do see an error on console:

ReferenceError: errorrr is not defined

I do not get an alert...


If I execute the same code, outside of the App's 'run', it works.

Why/How can I fix it?


Edit Using angular, I can't get to the $rootScope

angular.module('app').factory('$exceptionHandler', function ($log, $rootScope) {
    return function myExceptionHandler(exception, cause) {
        $log.error(exception, cause);
        $rootScope.errors.push({
            exception: exception,
            cause: cause
        });
    };
});

It throws

Circular dependency found: $rootScope <- $exceptionHandler <- $rootScope

Is there a way to get $rootscope within this factory?

Upvotes: 2

Views: 3268

Answers (1)

Amit
Amit

Reputation: 6294

As suggested in a comment to the question, using angular's own $exceptionHandler is preferable.

To fix the problem with circular injection, I needed to use the $injector service, like so:

angular.module('app').factory('$exceptionHandler', function ($log, $injector) {
    return function myExceptionHandler(exception, cause) {
        $log.error(exception, cause);
        var $rootScope = $injector.get('$rootScope');
        $rootScope.errors.push({
            string: exception.toString(),
            message: exception.message,
            lineNumber: exception.lineNumber,
            stack: exception.stack,
            cause: cause
        });
    };
});

Upvotes: 4

Related Questions