How do you handle errors in Express.js?

Why Interviewers Ask This

This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex Node.js topics. It also reveals how well you can explain technical ideas to non-experts.

Answer

Express.js has a special error-handling middleware with four parameters: (err, req, res, next). It must be defined after all other routes and middleware. Any route can trigger it by calling next(err) or by throwing an error in an async function (with appropriate wrapping). Structure: (1) In route handlers, pass errors to next(err) rather than crashing or sending ad-hoc error responses; (2) Create a centralized error handler: app.use((err, req, res, next) => { console.error(err.stack); res.status(err.status || 500).json({ error: err.message }); });; (3) For async route handlers, wrap with a try/catch that calls next: app.get("/", async (req, res, next) => { try { ... } catch(e) { next(e); } });. Libraries like express-async-errors or express-async-handler remove the need for repetitive try/catch boilerplate by automatically forwarding async errors to Express's error handler.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Node.js answers easy to follow.