This Express app checks if the ID is a number and if the item exists. It sends formatted error responses with status codes and JSON error messages.
import express from 'express';
const app = express();
app.use(express.json());
app.get('/item/:id', (req, res) => {
const id = req.params.id;
if (isNaN(id)) {
return res.status(400).json({ error: 'ID must be a number' });
}
if (id !== '1') {
return res.status(404).json({ error: 'Item not found' });
}
res.json({ id: 1, name: 'Sample Item' });
});
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: 'Internal server error' });
});
app.listen(3000, () => console.log('Server running on port 3000'));