Implement middleware functions in an Express.
js application to log incoming requests and handle
errors gracefully
const express = require('express');
const app = express();
const port = 3000;
// **Logging Middleware**
[Link]((req, res, next) => {
const currentTime = new Date().toISOString();
[Link](`[${currentTime}] ${[Link]} request to ${[Link]}`);
next(); // Pass control to the next middleware or route handler
});
// **Sample Route**
[Link]('/', (req, res) => {
[Link]('Hello, World!');
});
// Route that intentionally throws an error
[Link]('/error', (req, res) => {
throw new Error('This is a forced error!'); // Triggering an error
});
// **Error Handling Middleware**
[Link]((err, req, res, next) => {
[Link]([Link]); // Log the error stack for debugging
[Link](500).send('Something went wrong!'); // Send a generic error
response
});
// Start the server
[Link](port, () => {
[Link](`Server is running on [Link]
});