Javascript – catch errors using window.onerror

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:
javascript-window-onerror-demo

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>
refresh

Note that we introduced these three javascript errors (calling non existing functions):

  1. non_existing_function1();
  2. non_existing_function2();
  3. non_existing_function3();

Only first and third errors were caught. The second error was never reached.

How to use window.error

  1. It can be used in development environment to highlight errors.
  2. 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.
  3. Returning false from onerror handler will also invoke default javascript error handler. In case you want to skip that, return true;
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments