Node.js Basics
Node.js Error Handling
Node errors arrive in three ways: thrown exceptions in synchronous code, rejected promises in async code, and error events on streams and emitters. Each needs a different mechanism, and missing any one crashes the process.
What is Error Handling in Node.js?
Node errors arrive in three ways: thrown exceptions in synchronous code, rejected promises in async code, and error events on streams and emitters. Each needs a different mechanism, and missing any one crashes the process.
Error Handling example
JavaScript
// synchronous
try {
JSON.parse(raw);
} catch (err) {
console.error('Invalid JSON:', err.message);
}
// async
try {
const data = await readFile('config.json', 'utf8');
} catch (err) {
if (err.code === 'ENOENT') console.error('Config file missing');
else throw err;
}
// emitter — an unhandled 'error' event crashes the process
stream.on('error', err => console.error('Stream failed:', err));Custom errors carry useful context
JavaScript
class AppError extends Error {
constructor(message, statusCode = 500, code = 'INTERNAL') {
super(message);
this.name = 'AppError';
this.statusCode = statusCode;
this.code = code;
Error.captureStackTrace(this, this.constructor);
}
}
throw new AppError('Job not found', 404, 'JOB_NOT_FOUND');Key points to remember
- Check err.code rather than parsing err.message — messages change between versions.
- Handle process-level unhandledRejection and uncaughtException for logging, then exit.
- Never swallow an error silently; log it with enough context to act on.
Error codes you will meet constantly
| Code | Meaning |
|---|---|
| ENOENT | file or directory does not exist |
| EACCES | permission denied |
| EADDRINUSE | the port is already in use |
| ECONNREFUSED | nothing is listening at the target address |
| ETIMEDOUT | the operation took too long |
| ERR_MODULE_NOT_FOUND | an ES module import path is wrong |
Common mistakes with Error Handling
- An unhandled promise rejection, which terminates the process in modern Node.
- try/catch around a callback-style API, which never catches anything.
Node.js Error Handling— Interview Questions & FAQs
Why does my Node app crash with EADDRINUSE?+
Another process is already listening on that port — often a previous run that did not exit. Find it with lsof -i :3000 and stop it, or use a different port.
