Loading

Quipoin Menu

Learn • Practice • Grow

express-js / express-js - interview
interview

Q1. Why is the order of middleware important?
Middleware executes in the order they're defined. If you put body-parsing middleware after your route handlers, they won't parse the body before your handler runs. Order affects functionality: logging should come first, authentication before protected routes, error handlers last.

Q2. What is error-handling middleware?
Error-handling middleware takes four parameters: (err, req, res, next). It's used to catch and process errors. You define it after all other middleware and routes. Example: app.use((err, req, res, next) => { console.error(err); res.status(500).send('Something broke!'); });

Q3. How do you trigger error-handling middleware?
By passing an error to next(): next(err). Express skips all remaining regular middleware and goes to the next error-handling middleware. You can also throw errors in async code, but you must catch them and call next(err).

Q4. What happens if you don't handle errors?
Unhandled errors cause the server to crash or hang. Express has a default error handler that returns a 500 response, but it's basic. It's best to create custom error-handling middleware to log errors and send appropriate client responses.

Q5. Can you have multiple error-handling middleware?
Yes you can chain error-handling middleware. Each can check the error type and either handle it or pass to the next error handler. This allows specialized error handling (e.g. 404 handler validation errors database errors).
"