Loading

Quipoin Menu

Learn • Practice • Grow

express-js / express-js - interview
interview

Q1. How do you handle errors in Express async code?
Always wrap async route handlers in try-catch and pass errors to next(). Example: app.get('/data', async (req, res, next) => { try { const data = await fetchData(); res.json(data); } catch(err) { next(err); } }). Or use a wrapper like express-async-handler.

Q2. How do you create a global error handler?
Define error-handling middleware at the end of all routes with four parameters: (err, req, res, next). Log the error, then send appropriate response. Example: app.use((err, req, res, next) => { console.error(err); res.status(500).json({ error: err.message }); });

Q3. What are best practices for error handling?
Use custom error classes, distinguish between operational and programmer errors, don't leak stack traces in production, handle 404s separately, and log errors with tools like Winston or Morgan. Always validate input to prevent errors.

Q4. How do you debug Express applications?
Use console.log for simple debugging, but better: use debug module (npm install debug) for namespaced logging. Use Node.js inspector with Chrome DevTools: node --inspect app.js. Also use logging middleware like morgan to see request details.

Q5. What are some Express best practices?
Structure your app using MVC pattern, use environment variables for config, enable compression, use Helmet for security, implement rate limiting, validate input, use async/await, keep routes thin (logic in controllers), and test your code.