MDN self-hosted library · e01.org

Window: reportError() method

Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.

js
if (typeof window.reportError === "function") {
  // function is defined
}
js
window.addEventListener("error", (event) => {
  event.preventDefault(); // Prevent the default logging to console
  Sentry.captureException(event.error);
  console.error("Error encountered:", event.error);
  showToastNotification("An error occurred. Our team has been notified.");
});
js
function fetchUser(userId) {
  return fetch(`/api/users?id=${encodeURIComponent(userId)}`)
    .then((response) => {
      if (!response.ok) {
        throw new Error(`Failed to fetch user with ID ${userId}`);
      }
      return response.json();
    })
    .catch((error) => {
      // Report the error to the global error handler
      window.reportError(error);
    });
}