Handling exceptions in asynchronous code in Node.js requires a different approach than synchronous code, because try/catch
only works with synchronous blocks unless you're using async/await
.
Here’s how to handle exceptions properly in different async scenarios:
✅ 1. Using async/await
with try/catch
This is the most modern and readable method.
✅ 2. Handling Promise Rejections
If you're using .then()
/.catch()
, handle errors in .catch()
.
✅ 3. Global Unhandled Rejection Handling
Catch unhandled promise rejections globally (useful but shouldn't replace proper handling):
✅ 4. Callback Pattern (Legacy-style)
In older APIs using callbacks, check for errors manually:
✅ 5. Using Middleware in Express.js
For async route handlers, use a wrapper or next(err)
to pass errors:
Or use a helper like: