Express JS Express Error Handling 2 — Questions and Answers
Question 1: How can you create a custom error class with an HTTP status code for use with Express?
- Extend Error and add a status property (Correct answer)
- Use express.HttpError()
- Configure errors in app.settings
- Use the http-errors package only
Correct answer: Extend Error and add a status property
You can extend the built-in Error class and attach a status property to carry HTTP status codes through the error pipeline.
Question 2: What is the purpose of the http-errors package commonly used with Express?
- Creates HTTP-specific error objects with status codes and messages (Correct answer)
- Handles HTTPS redirects
- Logs HTTP errors to files
- Validates HTTP request formats
Correct answer: Creates HTTP-specific error objects with status codes and messages
http-errors creates error objects pre-populated with HTTP status codes, making it easy to send standardized error responses.
Question 3: Which Express middleware pattern handles 404 Not Found errors for unmatched routes?
- Add a catch-all app.use() at the end that calls next(createError(404)) (Correct answer)
- Use app.on('404', handler)
- Set app.notFound = handler
- Use app.error(404, handler)
Correct answer: Add a catch-all app.use() at the end that calls next(createError(404))
A catch-all middleware placed after all routes and before the error handler catches unmatched requests and generates a 404 error.
Question 4: How do you differentiate between development and production error responses in Express?
- Check process.env.NODE_ENV in the error handler and conditionally include stack traces (Correct answer)
- Use app.set('env', 'production')
- Use different app instances per environment
- Use NODE_ENV-specific route files
Correct answer: Check process.env.NODE_ENV in the error handler and conditionally include stack traces
By checking process.env.NODE_ENV, you can expose detailed stack traces in development while sending minimal info in production.
Question 5: What happens to errors thrown synchronously inside a route handler in Express?
- Express catches them automatically and passes them to the error handler (Correct answer)
- The app crashes
- They are silently ignored
- They are logged but not forwarded
Correct answer: Express catches them automatically and passes them to the error handler
Express wraps synchronous route handler code and automatically catches thrown errors, forwarding them to error-handling middleware.
Question 6: What property on an error object does Express use to set the response status code in the default error handler?
- err.status or err.statusCode (Correct answer)
- err.code
- err.httpCode
- err.responseCode
Correct answer: err.status or err.statusCode
Express's default error handler reads err.status or err.statusCode to determine the HTTP response status.
How can you create a custom error class with an HTTP status code for use with Express?