FSD-II Practical Assignmet 12
12. 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**
app.use((req, res, next) => {
const currentTime = new Date().toISOString();
console.log(`[${currentTime}] ${req.method} request to ${req.url}`);
next(); // Pass control to the next middleware or route handler }); // **Sample Route**
app.get('/', (req, res) => { res.send('Hello, World!'); }); // Route that intentionally throws an error
app.get('/error', (req, res) =>
{ throw new Error('This is a forced error!'); // Triggering an error });
// **Error Handling Middleware**
app.use((err, req, res, next) => { console.error(err.stack); // Log the error stack for debugging
res.status(500).send('Something went wrong!');
// Send a generic error response
});
// Start the server
app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); })
Comments
Post a Comment