Javascript errors can be caught using window.onerror event handler. Whenever a javascript error occurs browser calls this function. In this tutorial we’ll write error handler which will display javascript caught errors in an html <pre> tag as shown below:

Here is an html/javascript code snippet and rendered outcome for it.
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
window.myerr = "";
window.onerror = function (errorMsg, url, line) {
window.myerr += "[Error: " + errorMsg + "] [url: " + url + " ] [line: " + line + "]\n";
return false;
}
</script>
<script type="text/javascript">
non_existing_function1();
non_existing_function2();
</script>
<script type="text/javascript">
non_existing_function3();
</script>
Errors displayed by window.onerror handler:
<pre id="err" style="color:red;"></pre>
<script type="text/javascript">
$(function() {
$('#err').text(window.myerr);
});
</script>Note that we introduced these three javascript errors (calling non existing functions):
- non_existing_function1();
- non_existing_function2();
- non_existing_function3();
Only first and third errors were caught. The second error was never reached.
How to use window.error
- It can be used in development environment to highlight errors.
- In production it can be used to send errors back to server for critical flows. This way the health of the site/app can be monitored.
- Returning false from onerror handler will also invoke default javascript error handler. In case you want to skip that, return true;