How can I handle errors and log the stack trace in an Express.js application?

Question

Grade: Education Subject: Support
How can I handle errors and log the stack trace in an Express.js application?
Asked by:
77 Viewed 77 Answers

Answer (77)

Best Answer
(331)
In Express.js, you can use error-handling middleware. This middleware function takes four arguments: `err`, `req`, `res`, and `next`. Inside the middleware, you can log the error stack trace using `console.error(err.stack)` and then send an appropriate error response to the client using `res.status(500).send('Something broke!')`.