Skip to content Skip to sidebar Skip to footer

Detect All Js Errors, Using Js

I know this has probably been asked before, but I can't find where: I know you can detect JS errors using extensions in stuff, but is there any way to detect ALL errors using JavaS

Solution 1:

In the browser define the window.onerror function. In node attached to the uncaughtException event with process.on().

This should ONLY be used if your need to trap all errors, such as in a spec runner or console.log/ debugging implementation. Otherwise, you will find yourself in a world of hurt trying to track down strange behaviour. Like several have suggested, in normal day to day code a try / catch block is the proper and best way to handle errors/exceptions.

For reference in the former case, see this (about window.error in browsers) and this (about uncaughtException in node). Examples:

Browser

window.onerror = function(error) {
  // do something clever here
  alert(error); // do NOT do this for real!
};

Node.js

process.on('uncaughtException', function(error) {
  // do something clever here
  alert(error); // do NOT do this for real!
});

Solution 2:

uncaughtException must be added to browser. it will help to easily through Exceptions. tracing js errors, also.

Solution 3:

For JS in Browser

<!DOCTYPE html><htmllang="en"><head><script>var lastErr;
        functionerrHand(e) {
            lastErr = e;
            switch (e.target.nodeName) {
                case'SCRIPT':
                    alert('script not found: ' + e.srcElement.src);
                    break;
                case'LINK':
                    alert('css not found: ' + e.srcElement.href);
            }
            returnfalse;
        }
        window.onerror = function (msg, url, lineNo, columnNo, error) {
            alert(msg + ' - ' + url + ' - ' + lineNo + ' - ' + columnNo);
            returnfalse;
        }
    </script><scriptsrc="http://22.com/k.js"onerror="errHand(event)"></script><linkrel="stylesheet"href="http://22.com/k.css"onerror="errHand(event)"type="text/css" /></head><body><script>
        not_exist_function();
    </script></body></html>
  • This works for attached js files trace errors just in same origin host environment
  • For Request error handeling like Ajax/WebSocket its better use their Bulit-In functions
  • Console functions override not work for reading auto generated browser error logs at this time with latest browser updates

For NodeJS

process.on('uncaughtException', function (err) {
    console.error('uncaughtException:\n' + err.stack + '\n');
})

Use Both of them in the TOP of your codes

Post a Comment for "Detect All Js Errors, Using Js"