Get all javascript errors

5

How do I make catch of all errors in the javascript console?
I'm wanting to capture every error that plays during the site cycle and execute a function every time it happens. I am using Angular 1.6 .

I found that with the window.onerror I can get the errors but I do not capture those of Angular .

window.onerror = function (msg, url, lineNo, columnNo, error) {
  // ejecuto la función que quiero hacer
}
    
asked by Kleith 10.04.2018 в 14:37
source

2 answers

3

Try overwriting the provider $exceptionHandler . This captures all the errors that angular produces.

Here is an example:

var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
  
})
.factory('logErrorsToBackend',function(){
  return function(exception, cause) {
    console.log('guardando error en la base de datos');
  }
})
.factory('$exceptionHandler', ['$log','logErrorsToBackend', function($log, logErrorsToBackend) {
    return function myExceptionHandler(exception, cause) {
      alert('ha ocurrido un error');
      logErrorsToBackend(exception, cause);
      $log.warn(exception, cause);
    }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">

  {{asdfasf'}} <------- error de sintaxsis '

</div>
    
answered by 10.04.2018 / 16:13
source
-1

As explained in this MDN article, you can detect Javascript runtime errors in a window.onerror event handler MDN CODE:

export class ErrorLogService {

    private errors = new Array<any>();

    constructor() {
        let that = this;
        window.onerror = function (msg, url, lineNo, columnNo, error) {
            let string = msg.toLowerCase();
            let substring = "script error";
            if (string.indexOf(substring) > -1) {
                console.log("Script Error: See Browser Console for Detail");
            } else {
                that.errors.push({
                    message: msg,
                    url: url,
                    line: lineNo,
                    column: columnNo,
                    error: error
                });
            }
            return false;
        };
        window.document.addEventListener("error", (event: ErrorEvent) => {
            if (event.target && (event.target as any).src) {
                let url = (event.target as any).src;
                this.errors.push({
                    message: "Resource not found",
                    url: url
                });
            } else {
                this.errors.push({
                    message: "Unknown error",
                    error: event
                });
            }
        }, true);
    }
}

I HOPE YOU HELP !!

    
answered by 10.04.2018 в 15:33