How do you handle database errors in Node.js?
- Use try/catch blocks with async/await to catch exceptions.
- Handle errors in callbacks or promise .catch() when using promise-based APIs.
- Log errors for debugging.
- Return meaningful error messages to the client without exposing sensitive info.
Example:
try {
const user = await User.findById(id);
if (!user) throw new Error('User not found');
} catch (error) {
console.error(error);
res.status(500).send('Something went wrong');
}