Quiz Entry - updated: 2026.06.20
How should you handle database errors in Express with MongoDB?
Wrap every database call in a try/catch, log the real error server-side, and return a generic message with an appropriate HTTP status code.
try {
// insert / update / delete / find
} catch (error) {
console.error(error);
res.status(500).json({
message: 'server error while handling request'
});
}
Security: Never send raw error messages to clients - they may reveal database structure. Log detailed errors server-side, send generic messages to clients.