Express JS Express Error Handling 1 — Questions and Answers
Question 1: How many parameters must an Express error-handling middleware function declare?
- 4 (err, req, res, next) (Correct answer)
- 3 (err, req, res)
- 2 (err, next)
- 5 (err, req, res, next, app)
Correct answer: 4 (err, req, res, next)
Express identifies error-handling middleware by its four-parameter signature: err, req, res, and next.
Question 2: How do you pass a custom error to the Express error handler from a route?
- next(new Error('message')) (Correct answer)
- throw new Error('message')
- res.error(new Error('message'))
- app.error(new Error('message'))
Correct answer: next(new Error('message'))
Calling next() with an Error object routes the error to the next error-handling middleware.
Question 3: What is the default HTTP status code Express sends if an error reaches the error handler without res.status() being set?
- 500 (Correct answer)
- 404
- 400
- 503
Correct answer: 500
Express uses a 500 Internal Server Error status by default when an error reaches the error handler without an explicit status code.
Question 4: Which approach correctly handles errors in Express async route handlers?
- Wrap in try/catch and call next(err) (Correct answer)
- Use async/await without try/catch
- Use Promise.resolve()
- Express automatically catches async errors
Correct answer: Wrap in try/catch and call next(err)
Async errors must be caught with try/catch and forwarded via next(err), or wrapped with an async error handler utility.
Question 5: What does passing a string to next() (e.g., next('Something went wrong')) do in Express?
- Triggers the error-handling middleware with that string as the error (Correct answer)
- Logs the string to console
- Redirects to a route named by that string
- Sends a 400 response
Correct answer: Triggers the error-handling middleware with that string as the error
Passing any truthy value (including a string) to next() bypasses normal middleware and jumps to error handlers.
Question 6: In Express, where must error-handling middleware be placed relative to other middleware?
- At the very end, after all routes and other middleware (Correct answer)
- At the beginning, before routes
- Anywhere in the stack
- Inside individual route handlers
Correct answer: At the very end, after all routes and other middleware
Error-handling middleware must be the last middleware registered so it can intercept errors from all prior handlers.
How many parameters must an Express error-handling middleware function declare?