A. The status code is set after sending the response
B. The error message should not be sent in JSON
C. The middleware is missing the next() call
D. The error handler should not have four parameters
Solution
Step 1: Check order of response methods
Calling res.json() sends the response immediately. Setting status after sending has no effect.
Step 2: Correct order for setting status and sending response
Status must be set before sending JSON: res.status(500).json(...).
Final Answer:
The status code is set after sending the response -> Option A
Quick Check:
Status before sending response [OK]
Hint: Always set status before sending response [OK]
Common Mistakes:
Setting status after res.json()
Not sending status at all
Misunderstanding middleware parameters
5. You want to send a 422 Unprocessable Entity error with a JSON body containing { error: 'Invalid input', fields: ['name', 'email'] }. Which Express code snippet correctly formats this error response?
hard
A. res.json({ error: 'Invalid input', fields: ['name', 'email'] }).status(422);
B. res.status(422).json({ error: 'Invalid input', fields: ['name', 'email'] });
C. res.sendStatus(422).json({ error: 'Invalid input', fields: ['name', 'email'] });
D. res.status(400).json({ error: 'Invalid input', fields: ['name', 'email'] });
Solution
Step 1: Choose the correct status code and method order
Use res.status(422) to set the correct HTTP status code before sending JSON.
Step 2: Verify the JSON body matches the required error format
The JSON object includes both error and fields keys as specified.