Skip to content
jshacks.dev
Fundamentals

Error Handling Best Practices in JavaScript With Examples

Practical rules for JavaScript error handling: throw Error objects, add cause, catch narrowly, never swallow, handle async rejections and log once at the edge.

10 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the JavaScript, Node.js, Vite and npm logos.

Most error handling code in a typical JavaScript project is either missing or in the wrong place. A function that can fail has no try around its risky call, and a handler three layers up catches everything, logs a message, and carries on as if nothing happened. The language gives you the tools, throw, try, catch, finally, rejected promises and the Error class with its cause, and none of them tells you where to use which. This post is a set of rules we follow, each with the reason and a short example whose output you can check: what to throw, how to describe a failure, where to catch, how to treat asynchronous errors, what to log and when, how to separate expected failures from bugs, and how to test the failure path. The examples run on Node.js 24.

Throw Error objects, never strings

JavaScript lets you throw any value, and only an Error carries a stack trace and plays well with tools.

JavaScript
function failWithString() {
  throw "something broke";
}

function failWithError() {
  throw new Error("something broke");
}

for (const fn of [failWithString, failWithError]) {
  try {
    fn();
  } catch (error) {
    console.log(typeof error, error instanceof Error, "stack" in Object(error));
  }
}
Text
string false false
object true true

A thrown string has no stack, so a log line tells you what happened and not where. It also fails instanceof Error checks, and breaks code that reads error.message. Always throw new Error(...), or an instance of a class that extends Error. This is the rule with the least cost and the most return.

Say what failed, with context

An error message is for the person who reads the log at two in the morning. It should name the operation and the input that caused it.

JavaScript
function loadUser(id) {
  if (!Number.isInteger(id) || id <= 0) {
    throw new RangeError(`loadUser: id must be a positive integer, got ${JSON.stringify(id)}`);
  }
  return { id };
}

for (const input of [7, -1, "7", undefined]) {
  try {
    console.log(loadUser(input));
  } catch (error) {
    console.log(error.name, "-", error.message);
  }
}
Text
{ id: 7 }
RangeError - loadUser: id must be a positive integer, got -1
RangeError - loadUser: id must be a positive integer, got "7"
RangeError - loadUser: id must be a positive integer, got undefined

The message names the function and the rule, and shows the bad value with JSON.stringify, which makes the string "7" visibly different from the number. "Invalid input" would have been correct and useless. Use the built-in classes when they fit: TypeError for a wrong type, RangeError for a value outside its range, and a custom class for failures that belong to your domain.

Wrap errors with cause

When you catch an error to add context and throw again, keep the original as the cause. The cause chain is the history of the failure.

JavaScript
function readConfig(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    throw new Error("readConfig: could not parse the configuration", { cause: error });
  }
}

try {
  readConfig("{broken");
} catch (error) {
  console.log(error.message);
  console.log(error.cause.name);
  console.log(error.cause instanceof SyntaxError);
}
Text
readConfig: could not parse the configuration
SyntaxError
true

The outer error tells the caller what you were trying to do, and the inner one tells them why it failed. A handler can inspect error.cause when it needs the detail, and loggers that understand cause print the whole chain. Without it, you either lose the original error or paste its message into a string and lose its type.

Custom errors for your domain

A small class lets callers tell your failures from the rest, and carry data a caller can use.

JavaScript
class ValidationError extends Error {
  constructor(message, { field, cause } = {}) {
    super(message, { cause });
    this.name = "ValidationError";
    this.field = field;
  }
}

function validateEmail(email) {
  if (!email.includes("@")) {
    throw new ValidationError("email must contain @", { field: "email" });
  }
  return email;
}

try {
  validateEmail("ada");
} catch (error) {
  if (error instanceof ValidationError) {
    console.log(error.name, error.field, error.message);
  } else {
    throw error;
  }
}

console.log(new ValidationError("x") instanceof Error, Object.prototype.toString.call(new ValidationError("x")));
Text
ValidationError email email must contain @
true [object Error]

Setting name makes the class show up in logs, and the field property carries structured data. The catch block branches on the class and rethrows everything else, which is the next rule. Keep the hierarchy shallow: a few classes for the kinds of failure your callers handle differently, and not one per message.

Catch narrowly, and rethrow what you do not handle

A catch that swallows every error will also swallow your bugs.

JavaScript
function parseNumber(text) {
  try {
    const value = JSON.parse(text);
    return typeof value === "number" ? value : null;
  } catch (error) {
    if (error instanceof SyntaxError) return null;
    throw error;
  }
}

console.log(parseNumber("42"), parseNumber("oops"), parseNumber('"text"'));

try {
  parseNumber(Symbol("not text"));
} catch (error) {
  console.log("rethrown:", error.name);
}
Text
42 null null
rethrown: TypeError

The function expects one kind of failure, malformed JSON, and handles only that. A TypeError caused by passing a symbol is a programming mistake, and it propagates to a place where it will be seen. A broad catch { return null } would have hidden the mistake, and the caller would receive null for input that was never valid.

Do not use exceptions for ordinary control flow

An expected outcome is not an exceptional one. A lookup that finds nothing, or a user typing a wrong password, is part of the normal flow, and a return value says it better.

JavaScript
function findUser(users, id) {
  return users.find((user) => user.id === id) ?? null;
}

function parseAge(text) {
  const age = Number(text);
  return Number.isInteger(age) && age >= 0
    ? { ok: true, value: age }
    : { ok: false, reason: `not a valid age: ${text}` };
}

console.log(findUser([{ id: 1 }], 2));
console.log(parseAge("36"), parseAge("x"));
Text
null
{ ok: true, value: 36 } { ok: false, reason: 'not a valid age: x' }

Return null, undefined or a small result object for failures that callers expect and handle routinely, and throw for the cases where the caller cannot continue. A result object makes the expected failure visible in the type of the return value, and avoids the cost of building a stack trace for something that happens every day.

Always handle promise rejections

An asynchronous failure is a rejection, and it can be lost if nothing handles it.

JavaScript
async function loadData(fail) {
  if (fail) throw new Error("load failed");
  return "data";
}

async function main() {
  try {
    console.log(await loadData(false));
    console.log(await loadData(true));
  } catch (error) {
    console.log("caught:", error.message);
  }
}

await main();

const results = await Promise.allSettled([loadData(false), loadData(true)]);
console.log(results.map((r) => r.status));
Text
data
caught: load failed
[ 'fulfilled', 'rejected' ]

An await inside a try turns a rejection into an exception that the catch handles. A promise that is neither awaited nor given a .catch() produces an unhandled rejection, which, since Node.js 15, ends the process with an error by default. Promise.allSettled() is the tool when you want every outcome and no early exit. The common mistake is calling an async function without await and without handling its result, and a linter rule for floating promises catches it.

JavaScript
process.once("unhandledRejection", (reason) => {
  console.log("last resort:", reason.message);
});

loadData(true);
await new Promise((resolve) => setTimeout(resolve, 10));
Text
last resort: load failed

A process-level handler is a last resort for logging and shutting down cleanly, not a place to recover. By the time it runs, the program is in a state you did not plan for. Log the error, close what you can, and exit with a failure code.

Clean up in finally, or with using

Cleanup that must always run belongs where it will run on every path.

JavaScript
function withConnection(work) {
  const log = [];
  log.push("open");
  try {
    return work(log);
  } finally {
    log.push("close");
    console.log(log.join(" > "));
  }
}

withConnection((log) => log.push("query"));

try {
  withConnection(() => {
    throw new Error("query failed");
  });
} catch (error) {
  console.log(error.message);
}
Text
open > query > close
open > close
query failed

The finally block ran on success and on failure, and the error still reached the caller afterward. The newer using declaration does the same for objects with a dispose method, as covered in JavaScript Symbol.dispose. Do not return or throw from a finally block unless you mean to replace the outcome: a return there discards a pending error.

Log once, at the boundary

If every layer catches, logs and rethrows, the same failure appears five times in the log. Let errors propagate to the place where you can act on them, and log there, with the whole cause chain.

JavaScript
function describe(error, depth = 0) {
  const line = `${"  ".repeat(depth)}${error.name}: ${error.message}`;
  return error.cause instanceof Error ? `${line}\n${describe(error.cause, depth + 1)}` : line;
}

const root = new Error("connection refused");
const middle = new Error("query failed", { cause: root });
const top = new Error("could not load the user", { cause: middle });

console.log(describe(top));
Text
Error: could not load the user
  Error: query failed
    Error: connection refused

A single log entry shows the whole story, from what the caller asked for to the root cause. Add context as the error passes up, with cause, and log it once, at the edge: the request handler, the job runner or the top of the program. Do not log secrets, passwords or tokens in messages, and do not put the full user input in one without a length limit.

Map errors to responses at the edge

A server decides at the boundary what a failure means to the client.

JavaScript
class NotFoundError extends Error {
  name = "NotFoundError";
}

class ValidationError extends Error {
  name = "ValidationError";
}

function toResponse(error) {
  if (error instanceof ValidationError) return { status: 400, body: error.message };
  if (error instanceof NotFoundError) return { status: 404, body: "not found" };
  return { status: 500, body: "internal error" };
}

console.log(toResponse(new ValidationError("name is required")));
console.log(toResponse(new NotFoundError("user 7")));
console.log(toResponse(new TypeError("a bug")));
Text
{ status: 400, body: 'name is required' }
{ status: 404, body: 'not found' }
{ status: 500, body: 'internal error' }

Known failures become specific responses, and anything else becomes a generic 500, with the details logged on the server and not sent to the client. This is where the class hierarchy pays for itself: one function maps errors to the outside world, and the rest of the code throws meaningful errors.

Test the failure path

JavaScript
import assert from "node:assert/strict";

function divide(a, b) {
  if (b === 0) throw new RangeError("divide: b must not be zero");
  return a / b;
}

assert.throws(() => divide(1, 0), { name: "RangeError", message: /must not be zero/ });
assert.equal(divide(6, 3), 2);

await assert.rejects(async () => {
  throw new Error("async failure");
}, { message: "async failure" });

console.log("failure paths pass");
Text
failure paths pass

assert.throws checks a synchronous failure by class and message, and assert.rejects checks a rejected promise. A function with an error path and no test for it has an error path that is untested, and it will fail in production on its first real use. Test the class, not the full message, when the message may change.

A mistake we hit: the swallowed error with a default

JavaScript
function getConfigValue(config, key) {
  try {
    return config.settings[key];
  } catch {
    return "default";
  }
}

console.log(getConfigValue({ settings: { theme: "dark" } }, "theme"));
console.log(getConfigValue({}, "theme"));
console.log(getConfigValue(null, "theme"));
console.log(getConfigValue({ settings: { thme: "typo" } }, "theme"));
Text
dark
default
default
undefined

The function hid two real problems. A missing settings object and a null config both returned "default", so the program ran with the default and nobody learned the configuration was missing. The misspelled key returned undefined, not the default, because reading a missing property is not an error. We replaced the try with config?.settings?.[key] ?? "default", which says what is allowed to be missing, and left real mistakes to throw.

Choosing between the techniques

SituationDo this
A function cannot continueThrow an Error with a clear message
You add context to a caught errorThrow a new error with { cause }
A failure is expected and routineReturn a result or null
The caller must tell failures apartA small custom error class
An async function can rejectawait in try, or .catch()
Cleanup must always happenfinally, or using
A server request failsMap the error class to a status at the edge

Practical rules we follow

Throw Error objects with messages that name the operation and the value. Keep the original error as cause. Catch only what you can handle, and rethrow the rest. Do not use exceptions for expected outcomes. Await every promise. Log once at the boundary, with the cause chain, and without secrets. Test error paths. And keep a process-level handler as a last resort that logs and exits.

Where these rules stop

They cover application code. A library that other people call needs more care with its error types and documentation, so callers can rely on them. Browser code has window.onerror and unhandledrejection events, and frameworks have error boundaries. Distributed systems add timeouts, retries with backoff and circuit breakers, which are a topic of their own. The reference is in the MDN guide to control flow and error handling and the Node.js errors documentation.

Taggederrors
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.