0
0
Node.jsframework~5 mins

Handling uncaught exceptions in Node.js

Choose your learning style9 modes available
Introduction

Handling uncaught exceptions helps keep your Node.js app running smoothly by catching errors that were not handled anywhere else.

You want to log unexpected errors before the app crashes.
You need to clean up resources like files or database connections on errors.
You want to notify developers or admins about serious errors automatically.
You want to prevent the app from crashing immediately on unknown errors.
Syntax
Node.js
process.on('uncaughtException', (error) => {
  // handle the error here
});
Use process.on('uncaughtException') to catch errors not caught anywhere else.
After catching, it is best to log the error and safely shut down the app.
Examples
This example logs the error message when an uncaught exception happens.
Node.js
process.on('uncaughtException', (err) => {
  console.error('Error caught:', err.message);
});
This example logs the full error and then exits the app safely.
Node.js
process.on('uncaughtException', (err) => {
  console.error('Uncaught exception:', err);
  process.exit(1); // exit after handling
});
Sample Program

This program sets up a handler for uncaught exceptions. Then it calls a function that does not exist, causing an error. The handler catches it, logs the message, and exits the app.

Node.js
process.on('uncaughtException', (err) => {
  console.error('Caught an uncaught exception:', err.message);
  process.exit(1);
});

// This will cause an uncaught exception
nonExistentFunction();
OutputSuccess
Important Notes

Always log the error details to help with debugging.

It is recommended to exit the process after handling an uncaught exception to avoid unstable state.

Do not rely on this for normal error handling; use try-catch blocks where possible.

Summary

Use process.on('uncaughtException') to catch errors not handled elsewhere.

Log the error and exit the app safely to avoid unpredictable behavior.

This helps keep your Node.js app more stable and easier to debug.