Global Exception Handling in Node.js with Express
Global Exception Handling in Node.js with Express
Instead of throwing plain Error objects, we can create a custom error class that carries additional metadata — like HTTP status codes.
What's happening here?
- Extending Error → Our CustomException behaves like a normal JavaScript error.
- Status code field → Stores the HTTP status (e.g., 400, 404, 500).
- Prototype fix → Object.setPrototypeOf(...) ensures proper inheritance so instanceof checks work correctly.
- Helper method → getStatus() makes it easy to retrieve the status code.
This way, instead of just throwing an error message, we can throw something like:
Express allows us to define a special error-handling middleware. It must have four parameters: (err, req, res, next).
How it works
- If the error is an instance of CustomException, it responds with the custom status code and message.
- Otherwise, it falls back to a 500 Internal Server Error.
- Every unknown error is logged to the console for debugging.
This ensures your users always get a clean and safe response, while you keep detailed logs internally.
One tricky part of Express is async route handlers. If a Promise rejects, Express won't automatically catch it. That's why we wrap async routes in a helper:
Now, instead of writing:
We wrap it like this:
If an error occurs inside the async function, .catch(next) passes it directly to the global exception handler.
- Throw CustomException when you want controlled errors.
- Wrap routes with catchAsync to capture async errors.
- Register the global handler at the end of your Express app:
Why Use This Pattern?
- Consistency → All errors go through one central place.
- Security → You don’t accidentally leak stack traces to clients.
- Flexibility → Different error types can return different status codes/messages.
- Maintainability → Cleaner controllers without repetitive try/catch blocks.
Ready for Production
With this setup, your Node.js + Express application will have professional-grade error handling that's clean, safe, and easy to maintain.
Comments
Post a Comment