What is Error Handling?
Error handling is the process of catching and responding to unexpected issues that occur during execution—like invalid data, failed database queries, or broken APIs—without crashing the entire application.
Why is it Important?
- Prevents your server from crashing due to minor bugs.
- Helps show meaningful messages to frontend or users.
- Improves debugging and logs error causes efficiently.
How to Implement in Express?
- Use
try...catch blocks for async operations.
- Use centralized error-handling middleware.
- Send proper status codes (like 400, 500) and messages.
Example: Basic Error Handling with try...catch
app.get("/user/:id", async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: "User not found" });
res.json(user);
} catch (err) {
res.status(500).json({ error: "Server Error" });
}
});
Example: Centralized Error Handler
// middleware/errorHandler.js
function errorHandler(err, req, res, next) {
console.error(err.stack);
res.status(500).json({ message: "Something went wrong!" });
}
module.exports = errorHandler;
// Use it in server.js
const errorHandler = require('./middleware/errorHandler');
app.use(errorHandler);
When Should You Use It?
Implement error handling after your routes and logic are built, especially when:
- You're connecting to a database (MongoDB, MySQL).
- Calling 3rd-party APIs that may fail.
- Parsing request body or handling file uploads.
Best Practices
- Never expose internal errors to users.
- Log errors for later analysis using tools like
winston or morgan.
- Use status codes correctly: 400 for client errors, 500 for server errors.
References