const express = require('express');
const app = express();
// Parse JSON requests
app.use(express.json());
// Regular route
app.get('/', (req, res) => {
res.send('Welcome to the error handling demo. Try visiting /error-demo to see error handling in action.');
});
// Route that deliberately throws an error
app.get('/error-demo', (req, res, next) => {
try {
// Simulate an error
throw new Error('Something went wrong!');
} catch (error) {
next(error); // Pass error to the error handler
}
});
// Route with async error
app.get('/async-error', async (req, res, next) => {
try {
// Simulate an async error
await simulateAsyncError();
} catch (error) {
next(error);
}
});
// Error-handling middleware (must have 4 parameters)
app.use((err, req, res, next) => {
console.error('Error occurred:', err.stack);
// Send a formatted error response
res.status(500).json({
message: 'An error occurred',
error: process.env.NODE_ENV === 'production' ? {} : {
name: err.name,
message: err.message,
stack: err.stack
}
});
});
// Helper function to simulate async error
async function simulateAsyncError() {
return new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('Async operation failed'));
}, 100);
});
}
// Start the server
const PORT = 8080;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
// Simulate requests for demonstration
console.log('Simulating requests:');
// Simulate normal request
console.log('\nRequest to home route:');
console.log('GET /');
console.log('Response: Welcome to the error handling demo. Try visiting /error-demo to see error handling in action.');
// Simulate error request
console.log('\nRequest to error route:');
console.log('GET /error-demo');
console.error('Error occurred: Error: Something went wrong!');
console.log('Response:');
console.log(JSON.stringify({
message: 'An error occurred',
error: {
name: 'Error',
message: 'Something went wrong!',
stack: 'Error: Something went wrong! at ...'
}
}, null, 2));
});