Search code examples
javascriptdebuggingfeedback

Automatic feedback on JavaScript error


Is there a way to get an automatic feedback if an error (even syntax errors) occurs when running a JavaScript on the client side?

I was thinking of something like this:

<script src="debugger.js"></script>
<script>
    // some script with an error in it
</script>

And every time the debugger notices an error it sends a feedback to the server.


Solution

  • EDIT: I misunderstood your question initially, this should work:

    Also note, this needs to go BEFORE any javascript that might cause errors.

    window.onerror = function(msg,u,l)
    {
        txt ="Error: " + msg + "\n";
        txt+="URL: " + u + "\n";
        txt+="Line: " + l + "\n\n";
        //Insert AJAX call that passes data (txt) to server-side script
        return true;
    };
    

    As for syntax errors, you're out of luck. Javascript simply dies when there's a syntax error. There's no way to handle it at all.