TExcelTAD
Home › Node.js › Node.js Error Handling

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.

node · try it yourself
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', …)
node · try it yourself
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 EventEmitter that 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:

node · try it yourself
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.

node · try it yourself
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 Error objects, never strings; give custom errors a name.
  • Check err.code for system errors, and re-throw what you can't handle.
  • await every promise, or attach .catch().
  • Attach an 'error' listener to every emitter and stream (or use pipeline()).
  • In HTTP servers, turn errors into proper status codes and don't leak stack traces to clients.
  • Print err.message for users and log err.stack for developers.

Test yourself

What is the most reliable way to detect a 'file not found' error?

  1. err.message.includes('not found')
  2. err.code === 'ENOENT'
  3. err.name === 'FileError'
  4. err.status === 404

What happens when an EventEmitter emits 'error' and nobody listens for it?

  1. Nothing
  2. The error is logged and ignored
  3. The error is thrown, usually crashing the process
  4. The emitter retries

Which option keeps the original error when you wrap it in a new one?

  1. new Error(msg, { cause: err })
  2. new Error(msg, err)
  3. err.wrap(msg)
  4. Error.chain(err, msg)