DEV Community

Rostislav Jadavan
Rostislav Jadavan

Posted on

Effective exception handling in browser and Node.js

Exceptions in code are common, and sometimes they sneak by, causing problems for users that we might not see right away. In this article, I'm going to show you how to catch these tricky errors. This is also how tools like Sentry or WatchCat track and report them.

In javascript world, we deal with two main environments: Node.js running on servers and browsers running on users' devices. Each handles errors differently because of how they work.

Catching exceptions in browser

In the browser, handling exceptions revolves around the window.addEventListener method. This technique involves listening for the "error" event at the window level:

window.addEventListener("error", function (event) {
  console.error("Caught in browser:", event.message);
  // Additional error handling logic here
});
Enter fullscreen mode Exit fullscreen mode

See: https://developer.mozilla.org/en-US/docs/Web/API/Window/error_event

Node.js exception handling

For Node.js, there is the process.on method. This approach is split into handling synchronous exceptions with process.on("uncaughtException", ...) and asynchronous promise rejections with process.on("unhandledRejection", ...):

Uncaught Exception Handling:

process.on("uncaughtException", error => {
  console.error("Caught in Node.js:", error);
  // Error logging and cleanup before a graceful shutdown
});
Enter fullscreen mode Exit fullscreen mode

See: https://nodejs.org/api/process.html#event-uncaughtexception

Unhandled Rejection Handling:

process.on("unhandledRejection", (reason, promise) => {
  console.error("Unhandled Rejection:", reason);
  // Handle the unfulfilled promise here
});
Enter fullscreen mode Exit fullscreen mode

See: https://nodejs.org/api/process.html#event-unhandledrejection

In wrapping up, getting a handle on these error-catching methods for both browsers and Node.js can really make your web apps more solid and user-friendly. It's all about using the right approach for each environment to quickly catch and deal with those sneaky errors, improving our app's overall user experience.

Top comments (0)