Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 133 ยท The Runtime

Errors and Error Handling

Handle errors in Node.js properly - Error classes, error.cause, AggregateError, system error codes like ENOENT, error-first callbacks, uncaughtException, unhandledRejection and exit strategies.

Things go wrong in every program. A file is missing, the network drops, a user sends nonsense, a developer makes a typo. What separates a fragile program from a dependable one is not that it avoids errors, but that it notices them, explains them and recovers or stops safely. In Node.js, errors also travel in more ways than in most languages: thrown exceptions, rejected promises, callback arguments and 'error' events. Knowing which mechanism you are dealing with is half the battle.

This lesson starts with the Error object itself and the built-in types, moves on to the codes Node attaches to system failures, shows how to wrap errors without losing the original with error.cause, covers the four ways errors travel, and ends with the global safety nets and the question every Node developer has to answer: when an error is truly unexpected, should the process keep running? Production-grade practices continue in Error Handling in Production.

Anatomy of an Error

An Error is an ordinary object with a few special properties: name (the type, such as TypeError), message (a human-readable description) and stack (a string with the message and the call stack at the moment the error was created, not thrown). V8 builds the stack when you write new Error(...), which is why creating errors in a hot loop is slower than most objects.

The language has a small family of built-in types, and each has a typical cause:

  • TypeError: a value was not the type needed (null.x, calling something that is not a function).
  • ReferenceError: using a variable that does not exist.
  • SyntaxError: unparsable code, and also JSON.parse on bad text.
  • RangeError: a number outside a permitted range (new Array(-1), runaway recursion).
  • URIError, EvalError: rare.
  • AggregateError: several errors bundled together (more below).
Node.js Meeting the built-in error types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last two blocks make a point: always throw Error objects (or subclasses), never strings or plain objects. A thrown string has no stack trace, no name, and tools that check instanceof Error will mishandle it.

System errors and error codes

When Node's own APIs fail because of the operating system (a missing file, a refused connection, a busy port), they throw an Error with extra properties that are designed for programs to read:

  • code: a stable string such as 'ENOENT' (no such file), 'EEXIST' (already exists), 'EACCES' (permission denied), 'ECONNREFUSED', 'EADDRINUSE'.
  • syscall: the failing operation ('open', 'connect').
  • path (or address and port): what it was working on.
  • errno: the numeric operating-system code.

Node's own non-system errors also have codes, like ERR_INVALID_ARG_TYPE. Branch on error.code, never on error.message: the message is for humans and can change between versions or languages.

Node.js Reading a system error and branching on its code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the pattern in readOrDefault: handle the failure you expect and rethrow everything else. A bare catch { return fallback; } would also hide permission problems, disk errors and your own typos. Details of file errors are in Reading and Writing Files.

Custom errors

For your own failures, define classes that extend Error. They let callers use instanceof and give each failure a stable code and any useful data.

Node.js A custom error class with a code and extra data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

new.target.name sets name to the actual subclass, so you do not repeat it in each class. A shared base class like AppError lets an HTTP layer handle all your errors in one place and map status to a response, while anything that is not an AppError is treated as an unexpected bug.

error.cause: wrapping without losing the original

Often a low-level error is too vague by the time it reaches the code that can explain it. "ENOENT: no such file" does not tell the user that the configuration could not be loaded. The fix is to throw a new, more meaningful error and attach the original as its cause:

JavaScript
throw new Error('Could not load the configuration', { cause: originalError });

The cause chain is preserved and printed by console.log and by Node's crash output, with a [cause]: section for every level. You can walk it in code too.

Node.js Wrapping errors and walking the cause chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Each layer adds context for people reading the log and keeps the original for debugging. A good rule: add information as an error travels up, never delete it. Re-throwing a bare new Error(error.message) throws away the stack trace and the code.

AggregateError: several failures at once

When many things run together and several may fail, a single error is not enough. AggregateError holds an errors array. Promise.any throws one when all its promises reject. Promise.allSettled never rejects: it reports every outcome, which is the right tool when you want to attempt everything and then report all failures.

Node.js AggregateError and allSettled

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Four ways errors travel

The same failure can reach you in different shapes, and each needs its own handling. Mixing them up is the cause of most "my error handler never runs" bugs.

  1. Thrown exceptions from synchronous code: catch with try/catch.
  2. Rejected promises and async functions: await inside try/catch, or .catch(). A try/catch without await does not catch a rejection.
  3. Error-first callbacks: the oldest Node style. The first callback argument is the error (or null), the rest are results.
  4. 'error' events on emitters and streams: an 'error' listener; without one, the error is thrown (Events and EventEmitter).

Error-first callbacks

By convention, a Node callback is (error, result). You must check error first. You also cannot use try/catch around the call, because the callback runs later, from the event loop, outside the original stack.

Node.js Error-first callbacks, and turning them into promises

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The synchronous line from step 2 prints first, because the failures of steps 1 and 3 arrive later through the event loop. Do not depend on the relative order of the two asynchronous results. In new code prefer the promise versions (node:fs/promises); util.promisify converts old-style functions (see The util Module).

Rejections nobody handles

A promise that rejects with no handler attached is an unhandled rejection. Since Node 15 the default policy is to treat it like an uncaught exception: print the error and exit with code 1.

Node.js An unhandled rejection crashes the process (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The run prints a source excerpt, then Error: nobody caught me with a stack trace pointing at main.mjs:1, then the Node version line, and the exit code is 1. The timer message never appears, because the process died first. The cure is simple: every promise must be awaited or have a .catch. Also be careful with "fire and forget" calls, such as saveToDatabase(data); without await: their failures vanish into this crash.

Operational errors versus programmer errors

An important distinction, borrowed from Node's early community:

  • Operational errors are problems that can happen in a correct program: the network is down, a file is missing, the user typed bad input, a timeout fired. You expect them, handle them, and the program carries on.
  • Programmer errors are bugs: calling a function with the wrong argument, reading a property of undefined, a typo. The program is now in an unknown state. The right response is to fix the code, not to handle the error at runtime.

The distinction drives your design. Operational errors deserve try/catch at the places that know how to recover (retry, use a default, show a message). Programmer errors should not be swallowed; let them crash, log them loudly and fix them.

Node.js Classifying and handling errors differently

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The global safety nets

Two process events catch errors that nobody else handled. They exist for logging and cleanup before dying, not for carrying on as if nothing happened.

  • process.on('uncaughtException', (error, origin) => ...) fires when a thrown error reaches the top of the stack with no catch.
  • process.on('unhandledRejection', (reason, promise) => ...) fires for a rejected promise with no handler. When you add a listener, the default crash is replaced by whatever your handler does.
Node.js Observing uncaught exceptions and unhandled rejections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

With handlers installed, both errors are reported and the program continues, but the exit code ends up as 1 because we set it. That raises the key question.

Should the process continue after an unexpected error?

After an uncaughtException, the program state may be half-updated: a transaction open, a lock held, a connection in an odd state. Node's own guidance, and the recommendation here, is do not continue. Log the error, finish only the cleanup that is safe, and exit with a non-zero code. A supervisor (systemd, Docker, Kubernetes, PM2) then starts a fresh, clean process. This is the "crash and restart" strategy. The practical details, such as graceful draining of requests, are covered in Graceful Shutdown and Health Checks.

A sensible shape for the last-resort handler:

JavaScript
process.on('uncaughtException', (error) => {
  logger.fatal({ err: error }, 'uncaught exception, shutting down');
  // give the logger a moment to flush, then leave
  setTimeout(() => process.exit(1), 100).unref();
});

There is also process.on('uncaughtExceptionMonitor', fn), which observes the error (for crash reporting) without changing the default crash behaviour.

Habits that prevent most error bugs

  • Throw Error objects, with a code for anything callers might branch on.
  • Catch narrowly and rethrow the rest. An empty catch {} is a bug waiting to be discovered at 3 a.m.
  • Add context with cause, never overwrite or discard the original error.
  • Always await or .catch promises; use Promise.allSettled when you need every outcome.
  • Attach 'error' listeners to every stream, socket and emitter.
  • Do not use exceptions for normal control flow. Returning null or a result object for "not found" is cheaper and clearer than throwing for an everyday case.
  • Validate input at the boundary (HTTP handlers, CLI arguments, file contents) so bad data becomes a clear operational error early instead of a TypeError deep inside.
  • Keep stack traces useful. Source maps and --enable-source-maps make errors from transpiled code point at your original files; see Debugging and Diagnostics.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which property should you inspect to decide how to handle a failed file read, such as a missing file?

    code is a stable identifier designed for programs. Messages are for humans and may change.
  2. 2. What does the cause option do in new Error('Could not start', { cause: err })?

    The original error becomes error.cause. Node prints it as [cause] and tools can walk the chain.
  3. 3. You call an async function without await inside try/catch, and it rejects. What happens?

    try/catch only sees rejections when the promise is awaited inside it.
  4. 4. Which is a programmer error rather than an operational error?

    Operational errors can happen in correct programs. A TypeError from a bug means the code must be fixed.
  5. 5. What is the recommended reaction to an 'uncaughtException' in production?

    After an uncaught exception the program state is unreliable, so crash-and-restart is the safe strategy.

Summary

  • Errors have name, message and stack; always throw Error objects, never strings.
  • Built-in types (TypeError, RangeError, SyntaxError, ...) signal the kind of failure; system errors add code, syscall, path and errno. Branch on code.
  • Define custom error classes with a stable code and extra fields; share a base class for your application.
  • Use { cause } to wrap and add context without losing the original; AggregateError, Promise.any and Promise.allSettled handle multiple failures.
  • Errors travel as exceptions, rejected promises, error-first callbacks and 'error' events; each has its own handling.
  • Unhandled rejections crash the process by default; always await or catch promises.
  • Handle operational errors where you can recover; treat programmer errors as bugs. After an uncaughtException, log, clean up and exit so a supervisor can restart.

Next: The util Module