Global error catch

In the browser we can assign a function to the special window.onerror property, that will run in case of an uncaught error.

Node.js has process.on(“uncaughtException”) for this.

Syntax:


window.onerror = function(message, url, line, col, error) {
  // ...
};

Example:

<script>
  window.onerror = function(message, url, line, col, error) {
    alert(`${message}\n At ${line}:${col} of ${url}`);
  };

  function readData() {
    badFunc(); // Whoops, something went wrong!
  }

  readData();
</script>

There are also web-services that provide error-logging for such cases, like https://errorception.com or http://www.muscula.com.

They work like this:

  • We register at the service and get a piece of JS (or a script URL) from them to insert on pages.
  • That JS script sets a custom window.onerror function.
  • When an error occurs, it sends a network request about it to the service.
  • We can log in to the service web interface and see errors.