How do errors in a web page reach the dev console?

When you write throw new Error("blah") in JavaScript, this often results in a message in the console. What are the steps that lead to this message?

First, we go up the call stack until the nearest catch block. If there is no catch block, an ErrorEvent is created, and window.dispatchEvent is called with it. These errors can be observed by adding an event listener:

window.addEventListener("error", (errorEvent) => {
  // ...
});

The browser’s console is one such event listener. We can see this by cancelling the events before they reach the console output:

window.addEventListener("error", (errorEvent) => {
  errorEvent.preventDefault();
});

Despite GPT-4’s beliefs, throw new Error() does not propagate through the DOM tree. If you throw an error in a button click event listener, the error does is not dispatched on the button element, and it does not bubble up to the button’s ancestor elements. The error event is dispatched directly on the window object.

However, other events do propagate through the DOM. If an image fails to load, an “error” event is dispatched on the image element. This event does not bubble, but it does have a capture phase. We can capture these resource errors in their capture phase using:

window.addEventListener("error", (errorEvent) => {
  // ...
}, true);
Tagged #programming, #web.

Similar posts

More by Jim

👋 I'm Jim, a full-stack product engineer. Want to build an amazing product and a profitable business? Read more about me or Get in touch!

This page copyright James Fisher 2024. Content is not associated with my employer. Found an error? Edit this page.