Error Handling in Node.js
Handle synchronous and asynchronous errors gracefully in Node.js and Express, including custom error classes and centralized error middleware.
Handle synchronous and asynchronous errors gracefully in Node.js and Express, including custom error classes and centralized error middleware.
Here's everything this chapter covers, in the order you'll learn it:
- Synchronous errors
- Asynchronous errors
- try...catch for sync and async code
- Express error-handling middleware
- Custom error classes
- Mapping errors to HTTP status codes
- Validation error responses
- Database error handling
- Logging errors properly
- Hiding internal details in production error messages
- Handling unhandledRejection events
- Graceful shutdown on fatal errors
app.use((error, request, response, next) => {
console.error(error);
response.status(500).json({
message: "Internal server error",
});
});
- Express error-handling middleware is recognized by having FOUR parameters: (error, request, response, next) โ this exact signature is required.
- Never leak stack traces or internal error details to API clients in production โ log them internally, but return a generic message externally.
Q What's the most important thing to understand about error handling in node.js?
Focus on: try/catch ยท Error Middleware ยท Custom Error Classes ยท Unhandled Rejections ยท Graceful Shutdown. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Do I need external npm packages for error handling in node.js?
Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ otherwise, this chapter relies entirely on Node.js's own built-in capabilities.