0% found this document useful (0 votes)
20 views2 pages

Express.js Middleware for Logging & Errors

Uploaded by

nikhil patil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views2 pages

Express.js Middleware for Logging & Errors

Uploaded by

nikhil patil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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]
});

You might also like