17

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?

12
  • 7
    Wrap everything in try ... catch Commented Dec 12, 2013 at 3:25
  • @argo49 i need a way to detect it from the script, not the console Commented Dec 12, 2013 at 3:25
  • Nope, javascript execution generally halts on errors. You could wrap everything in try / catch, but it would probably be better to not write code with errors in it, or at least just use the console to fix them. Commented Dec 12, 2013 at 3:26
  • @Barmar would that work? Just put ALL script in a try/catch? Commented Dec 12, 2013 at 3:26
  • 1
    It won't work for callback functions, though, since they're called outside the dynamic scope of the try. Commented Dec 12, 2013 at 3:27

3 Answers 3

28

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 behavior. 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
  console.log(error);
};

Node.js

process.on('uncaughtException', function(error) {
  // do something clever here
  console.log(error);
});
Sign up to request clarification or add additional context in comments.

3 Comments

How do you try / catch script errors from 3rd party scripts, which you cannot edit?
If a 3rd party script crashes then there is a bug in their script and the 3rd party needs to informed so they can fix it. Maybe consider an alternative script or wrap your interface to their script with your own code that knows how to handle errors. For sync calls into a 3rd party lib wrap the call in a try/catch. For async 3rd party libs wrap the calls in a Promise constructor.
nice, but alert is not built-in function in nodejs, its an extra package... its better u update it to console.log
0

For JS in Browser

<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        var lastErr;
        function errHand(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);
            }
            return false;
        }
        window.onerror = function (msg, url, lineNo, columnNo, error) {
            alert(msg + ' - ' + url + ' - ' + lineNo + ' - ' + columnNo);
            return false;
        }
    </script>
    <script src="http://22.com/k.js" onerror="errHand(event)"></script>
    <link rel="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

Comments

0

A simple way to detect errors in JavaScript code executed by a webpage is always to call top-level js functions via a js utility function CallJS, included below.

For initialization code: Place CallJS(Init) at start of your js file. For an event handler such as onclick place this in the HTML file: <element "CallJS(OnClick)">.

Here is the utility function:

function CallJS(func)
    {
try
    {
    func(event); // Call the given function
    }
catch(e) // e is the Error object
    {
    const
        name=e['name'],
        message=e['message'],
        stack=new Error().stack;
    let $msg=YOUR_ERROR_MESSAGE+stack;
    throw(e); // Rethrow to show error in Console
    } // catch
    } // CallJS

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.