Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 JavaScript and display an alert whenever there is one?

like image 425
markasoftware Avatar asked Dec 12 '13 03:12

markasoftware


People also ask

How do I check for JavaScript errors?

Right-click anywhere in the webpage and then select Inspect. Or, press F12 . DevTools opens next to the webpage. In the top right of DevTools, the Open Console to view errors button displays an error about the webpage.

How many errors are there in JavaScript?

There are 7 types of JavaScript errors: Syntax error, Reference Error, Type Error, Evaluation Error, RangeError, URI Error and Internal Error.


1 Answers

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!
});
like image 177
Sukima Avatar answered Sep 20 '22 17:09

Sukima