app.use((err, req, res, next) => {
if (err.isValidationError) {
return res.status(400).json({
error: {
message: err.message,
fields: err.fields
}
});
}
next(err);
});The middleware sends a JSON response with a top-level error key containing an object with message and fields. Option A matches this structure exactly.
Option C correctly chains status(422) and json() to send a JSON response with status 422. Option C misses the error key. Option C uses send which works but json is preferred for JSON. Option C uses deprecated syntax.
app.use((err, req, res, next) => {
if (err.isValidationError) {
res.status(400);
res.json({ error: err.message });
return;
}
next(err);
});Calling next(err) after sending a response passes control to the next error handler, which may overwrite or end the response prematurely. The middleware should return after sending the response to prevent this.
app.use((err, req, res, next) => {
if (err.isValidationError) {
res.status(422).json({
error: {
message: err.message,
invalidFields: err.invalidFields
}
});
} else {
res.status(500).json({ error: "Internal Server Error" });
}
});The handler sends status 422 with an error object containing message and invalidFields. Option D matches this exactly.
Consistent JSON error objects with message and details allow clients to parse and display errors clearly. Options B, C, and D go against common API design best practices.