Good error handling keeps your app running and makes problems easy to find.
Two kinds of errors
- Operational errors — expected problems: invalid input, file not found, database down. Handle them and return a clear message.
- Programmer errors — bugs:
undefined is not a function. Fix the code; often the safest action is to log and restart.
Tools
try / catcharoundawait.catch()on promise chainsthrow new Error('message')- Custom error classes —
class NotFoundError extends Errorwith astatusCode error.cause— keep the original error:new Error('Save failed', { cause: err })
Last line of defence
process.on('unhandledRejection', ...)— a promise rejected with no catchprocess.on('uncaughtException', ...)— a thrown error nobody caught
Log the error, close the server cleanly, and exit with process.exit(1). A process manager (PM2, Docker, systemd) restarts the app.
Never show stack traces to users in production — log them instead.
Example
Example — Custom errors and safe shutdown
JavaScript
class AppError extends Error {
constructor(message, statusCode = 500) {
super(message);
this.name = 'AppError';
this.statusCode = statusCode;
}
}
class NotFoundError extends AppError {
constructor(what) { super(`${what} not found`, 404); }
}
async function getProduct(id) {
const products = { 1: 'Pen', 2: 'Notebook' };
if (!products[id]) throw new NotFoundError(`Product ${id}`);
return products[id];
}
try {
console.log(await getProduct(1)); // Pen
console.log(await getProduct(9));
} catch (err) {
if (err instanceof AppError) console.log(err.statusCode, err.message); // 404 Product 9 not found
else throw err;
}
process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection:', reason);
process.exit(1);
});
Prints Pen, then 404 Product 9 not found. Any promise rejection that nobody handles is logged and the process exits so a process manager can restart it.