📍 1. What is Error Handling?
A: Error handling is the process of catching and responding to errors that occur during request processing, ensuring the server doesn’t crash and clients get meaningful messages.
📍 2. Built-in Error Handling
- Express automatically catches errors in synchronous routes.
- Example:
app.get('/error', (req, res) => {
throw new Error('Something went wrong!');
});📍 3. Custom Error-handling Middleware
- Middleware with 4 parameters
(err, req, res, next) handles errors globally. app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send({ message: err.message });
});📍 4. Try-Catch in Async Functions
- Async route handlers need try-catch to handle errors.
app.get('/async', async (req, res, next) => {
try {
const data = await getData();
res.send(data);
} catch (err) {
next(err);
}
});📍 5. Sending Proper Status Codes
- 400 → Bad Request
- 401 → Unauthorized
- 403 → Forbidden
- 404 → Not Found
- 500 → Internal Server Error
📍 6. Error Logging
- Use
console.error() or logging libraries like winston or morgan for debugging.📍 7. Best Practices
- Keep error messages user-friendly.
- Don’t expose stack traces in production.
- Centralize error handling.
- Validate inputs to prevent errors early.
💬 Tap ❤️ for more!