Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can read browser error using javascript or angular2?

I need to append these error in the log file on back-end. These error are not captured in angular2. How can read these error?Browser console snapshot

like image 977
Rohit Avatar asked May 05 '17 10:05

Rohit


Video Answer


1 Answers

As explained in this MDN article, you can catch Javascript runtime errors in a window.onerror event handler, and catch resource loading errors in a capturing event handler defined with window.addEventListener("error", fn, true).

A service could set these event handlers and record the errors in an array. You would send the content of the array to the server when you want. The service could look like this:

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);
    }
}

The error detection mechanism can be tested in this jsfiddle.

like image 173
ConnorsFan Avatar answered Sep 21 '22 12:09

ConnorsFan