Node.js Error Handling
Things go wrong in every real program: a file is missing, a network request times out, a user sends invalid JSON. Good error handling means two things — recover from the errors you expect, and fail loudly and safely on the ones you don't. In a server, an unhandled error can crash the whole process and drop every connection, so this matters more in Node.js than in a browser tab.
Two kinds of errors
| Kind | Examples | What to do |
|---|---|---|
| Operational (expected) | file not found, invalid input, network timeout, duplicate key | handle it: retry, use a default, return a 4xx/5xx response |
| Programmer (bugs) | undefined is not a function, wrong argument types |
fix the code; let the process crash and restart |
Error objects and codes
Always throw Error objects (or subclasses), never plain strings — only Errors carry a stack trace. Node's system errors also have a code property such as ENOENT. Check the code, not the message: messages can change between versions, codes are stable.
const fs = require('node:fs');
try {
fs.readFileSync('does-not-exist.txt', 'utf8');
} catch (err) {
console.log(err instanceof Error);
console.log(err.code);
console.log(err.syscall);
}
try {
JSON.parse('{ bad json }');
} catch (err) {
console.log(err.name);
}
try {
null.length;
} catch (err) {
console.log(err.name);
}true
ENOENT
open
SyntaxError
TypeError
Common system error codes:
| Code | Meaning |
|---|---|
ENOENT |
no such file or directory |
EACCES / EPERM |
permission denied |
EEXIST |
file already exists |
EADDRINUSE |
port is already in use |
ECONNREFUSED |
nothing is listening at that address |
ETIMEDOUT |
the operation timed out |
Errors in async code
How you catch an error depends on how the API reports it:
| Style | How errors arrive | How to catch |
|---|---|---|
| synchronous | thrown | try…catch |
| callback | first argument err |
if (err) … |
promise / async |
rejection | try…catch around await, or .catch() |
EventEmitter / stream |
'error' event |
emitter.on('error', …) |
import { readFile } from 'node:fs/promises';
import { EventEmitter } from 'node:events';
async function loadConfig(path) {
try {
return JSON.parse(await readFile(path, 'utf8'));
} catch (err) {
if (err.code === 'ENOENT') {
console.log('no config file, using defaults');
return { port: 3000 };
}
throw err; // unexpected: let the caller deal with it
}
}
console.log(await loadConfig('config.json'));
const emitter = new EventEmitter();
emitter.on('error', (err) => console.log('emitter error:', err.message));
emitter.emit('error', new Error('connection lost'));no config file, using defaults
{ port: 3000 }
emitter error: connection lost
Note: An
EventEmitterthat emits'error'with no'error'listener throws, which usually crashes the process. Always attach an error listener to streams, sockets and servers.
Custom error classes
Subclass Error to give errors a name, extra data, and something you can check with instanceof. The cause option (ES2022) wraps a lower-level error without losing it:
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError';
this.field = field;
this.status = 400;
}
}
function parseAge(input) {
const age = Number(input);
if (!Number.isInteger(age) || age < 0) {
throw new ValidationError('age', `"${input}" is not a valid age`);
}
return age;
}
function loadUser(json) {
try {
const data = JSON.parse(json);
return { name: data.name, age: parseAge(data.age) };
} catch (err) {
throw new Error('could not load user', { cause: err });
}
}
for (const json of ['{"name":"Ana","age":"31"}', '{"name":"Bo","age":"-4"}', 'oops']) {
try {
console.log(loadUser(json));
} catch (err) {
const cause = err.cause;
console.log(err.message, '<-', cause.name + ':', cause.message);
if (cause instanceof ValidationError) console.log(' field:', cause.field, 'status:', cause.status);
}
}{ name: 'Ana', age: 31 }
could not load user <- ValidationError: "-4" is not a valid age
field: age status: 400
could not load user <- SyntaxError: Unexpected token 'o', "oops" is not valid JSON
The last line of defence
If an error escapes every try…catch, Node emits a process-level event. By default an uncaught exception or unhandled promise rejection prints the stack trace and exits with code 1.
process.on('unhandledRejection', (reason) => {
console.log('unhandled rejection:', reason.message);
process.exitCode = 0; // only so this example finishes as "successful"
});
process.on('exit', (code) => console.log('exit code', code));
async function forgotToCatch() {
throw new Error('nobody awaited me');
}
forgotToCatch(); // no await, no .catch()
console.log('main code finished');main code finished
unhandled rejection: nobody awaited me
exit code 0
Tip: Use
process.on('uncaughtException')and'unhandledRejection'only to log the error and shut down cleanly — not to keep running. After an unexpected error the program's state may be corrupt. Let a process manager (systemd, Docker, PM2, Kubernetes) restart it.
Checklist
- Throw
Errorobjects, never strings; give custom errors aname. - Check
err.codefor system errors, and re-throw what you can't handle. awaitevery promise, or attach.catch().- Attach an
'error'listener to every emitter and stream (or usepipeline()). - In HTTP servers, turn errors into proper status codes and don't leak stack traces to clients.
- Print
err.messagefor users and logerr.stackfor developers.
Test yourself
What is the most reliable way to detect a 'file not found' error?
err.message.includes('not found')err.code === 'ENOENT'err.name === 'FileError'err.status === 404
What happens when an EventEmitter emits 'error' and nobody listens for it?
- Nothing
- The error is logged and ignored
- The error is thrown, usually crashing the process
- The emitter retries
Which option keeps the original error when you wrap it in a new one?
new Error(msg, { cause: err })new Error(msg, err)err.wrap(msg)Error.chain(err, msg)