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

Popular posts from this blog

Slip 11: Write node js application that transfer a file as an attachment on web and enables browser to prompt the user to download file using express js.

Slip 7 Create a node js file named main.js for event-driven application. There should be a main loop that listens for events, and then triggers a callback function when one of those events is detected.

Slip 1(a) Write an Angular 13 application addition of two numbers using ng-init, ng-model & ng-bind. And also demonstrate ng-show, ng-disabled, ng-click directives on button component.