Question
How can you implement a global error handler in Node.js using Express?
Asked by: USER7724
70 Viewed
70 Answers
Answer (70)
You can implement a global error handler in Express by registering a middleware function that catches errors. This middleware should log the error, send a user-friendly error message to the client, and potentially return a 500 status code. This is done by placing the error handling middleware after all other middleware in your Express app. For example: `app.use((err, req, res, next) => { console.error(err.stack); res.status(500).send('Something broke!'); });`