How to catch specific error types in JavaScript

How to catch specific error types in JavaScript

“Something went wrong” is not a useful error category. A missing optional configuration file, invalid user input, a failed network request, and a bug in the program may all arrive through the same catch block, but they call for different responses. Decide which failures the current operation can handle before writing the recovery path.

Prefer a documented error type or code over parsing a message. Messages are for people; wording can change, be localized, or include details that make exact matching brittle. For example, Node.js file-system errors expose stable codes that distinguish a missing file from a permissions problem:

import { readFile } from "node:fs/promises";

async function readSettings(path) {
  try {
    return await readFile(path, "utf8");
  } catch (error) {
    if (error && error.code === "ENOENT") {
      return "{}";
    }

    throw error;
  }
}

The fallback is appropriate only because a missing settings file is an expected condition for this operation. A permission failure is not equivalent: silently returning defaults would hide a deployment or access-control problem. Likewise, a broad fallback can turn an unrelated defect into plausible but incorrect behavior.

When an API does not provide a stable code, use the error’s documented type rather than its message. Keep the decision close to the operation that understands the failure, and let failures outside that operation’s responsibility propagate unchanged.

Use instanceof for built-in errors

JavaScript’s built-in error classes let a handler distinguish familiar failure categories without depending on message text. For example, JSON.parse reports malformed JSON with a SyntaxError. If malformed input is an expected condition, handle that type and allow other failures to escape:

function parseSettings(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    if (error instanceof SyntaxError) {
      return {};
    }

    throw error;
  }
}

Use the type only when it identifies a failure this operation can meaningfully handle. A TypeError might indicate invalid data from a caller, but it might also expose a programming mistake inside the operation. Catching every TypeError and substituting a default can conceal the latter.

instanceof ordinarily checks the error’s prototype chain, so it works when the error and the handler use the same JavaScript realm. Errors created in another realm, such as an iframe or a Node.js virtual machine context, may fail the check even when they represent the same built-in error type. For cross-realm boundaries, prefer a documented error code or another contract supplied by the API.

Also, JavaScript permits throwing values that are not Error objects. A type check simply fails for such a value; rethrowing it preserves the original failure rather than accidentally treating it as an expected built-in error:

function loadDocument(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    if (error instanceof SyntaxError) {
      throw new Error("The document is not valid JSON", { cause: error });
    }

    throw error;
  }
}

Define custom error classes

When an operation has a failure category that callers need to handle, give it a distinct error class. The class becomes part of the operation’s contract: callers can test the type without relying on message wording, and the error can carry structured details relevant to recovery.

class SettingsFormatError extends Error {
  constructor(path, options) {
    super(Settings file is invalid: ${path}, options);
    this.name = "SettingsFormatError";
    this.path = path;
  }
}

Use the built-in cause option to retain the lower-level failure when translating it. The new error communicates what the operation means by that failure; its cause preserves the diagnostic detail that produced it:

import { readFile } from "node:fs/promises";

async function readSettings(path) {
  let text;

  try {
    text = await readFile(path, "utf8");
  } catch (error) {
    throw error;
  }

  try {
    return JSON.parse(text);
  } catch (error) {
    if (error instanceof SyntaxError) {
      throw new SettingsFormatError(path, { cause: error });
    }

    throw error;
  }
}

Wrapping is useful when it adds meaning at an abstraction boundary, not merely to change the error’s appearance. Avoid discarding the original error or copying its message into a new one as the sole record of what happened. A cause chain lets a caller respond to the domain-level failure while logs and diagnostics can still inspect the underlying exception.

Callers can now handle this specific condition and leave unrelated failures untouched:

try {
  return await readSettings(path);
} catch (error) {
  if (error instanceof SettingsFormatError) {
    reportInvalidSettings(error.path, error.cause);
    return {};
  }

  throw error;
}

Keep custom classes focused on stable facts that callers can use. A path, resource identifier, or documented error code is often more useful than a message fragment. Do not make callers infer behavior by parsing prose, and do not create a separate class for every incidental detail unless callers genuinely need to distinguish those cases.

Catch narrowly and rethrow unexpected errors

A catch block should cover only the operation whose failure it knows how to interpret. If a larger block includes parsing, validation, and unrelated work, an exception from any of those steps may be mistaken for the failure the handler was meant to recover from.

function parseSettings(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    if (error instanceof SyntaxError) {
      throw new SettingsFormatError("settings", { cause: error });
    }

    throw error;
  }
}

async function loadSettings(path) {
  const text = await readFile(path, "utf8");
  const settings = parseSettings(text);
  validateSettings(settings);
  return settings;
}

Here, only the parsing operation is inside the handler. A failure from readFile or validateSettings cannot be confused with malformed JSON. The handler translates the one error it understands and rethrows every other thrown value unchanged.

Rethrowing the original value preserves its type, properties, and stack information. Do not replace an unexpected error with a generic one merely to make it look uniform; doing so can erase information needed by callers and diagnostics.

try {
  await saveRecord(record);
} catch (error) {
  if (error instanceof DuplicateRecordError) {
    return findExistingRecord(record.id);
  }

  throw error;
}

Keep cleanup separate from recovery. A finally block runs whether the operation succeeds or fails, while a catch block should alter control flow only for failures the current operation can handle:

const connection = await openConnection();

try {
  return await connection.query(statement);
} finally {
  await connection.close();
}

If cleanup itself can fail, define how that failure relates to an error already in flight. A cleanup exception can otherwise replace the original failure, making the symptom appear unrelated to the operation that failed.

Test error handling at the right boundary

Test error handling where the program makes the decision to recover, translate, or propagate—not merely where an error is constructed. A test of the custom error class alone cannot show that callers receive it, that its cause is retained, or that an unrelated failure escapes unchanged.

For example, test the public operation’s behavior for malformed input and for a failure from a dependency. Injecting the dependency makes the latter case deterministic without relying on operating-system permissions or other environmental details:

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

async function loadSettings(path, readText) {
  const text = await readText(path);

  try {
    return JSON.parse(text);
  } catch (error) {
    if (error instanceof SyntaxError) {
      throw new SettingsFormatError(path, { cause: error });
    }

    throw error;
  }
}

test("translates malformed settings and preserves the cause", async () => {
  await assert.rejects(
    loadSettings("settings.json", async () => "{"),
    error =>
      error instanceof SettingsFormatError &&
      error.path === "settings.json" &&
      error.cause instanceof SyntaxError
  );
});

test("propagates failures from the reader unchanged", async () => {
  const failure = new Error("read failed");

  await assert.rejects(
    loadSettings("settings.json", async () => {
      throw failure;
    }),
    error => error === failure
  );
});

Assertions should target the contract callers rely on: the error type, stable fields, cause, fallback value, or identity of a propagated error. Avoid asserting exact message text unless the message itself is part of the documented interface; otherwise a harmless wording change can break a test without changing behavior.

Source: https://www.jsfaq.com/how-to-catch-specific-error-types-in-javascript/


You might also like this video

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply