typestar

Errors that carry a cause in JavaScript

A custom Error subclass, with the original attached.

class ConfigError extends Error {
  constructor(message, options) {
    super(message, options);
    this.name = "ConfigError";
  }
}

function parsePort(text) {
  try {
    const port = Number.parseInt(text, 10);
    if (Number.isNaN(port)) throw new TypeError(`not a number: ${text}`);
    return port;
  } catch (error) {
    throw new ConfigError("port is invalid", { cause: error });
  }
}

try {
  parsePort("http");
} catch (error) {
  console.log(error.name, error.message);
  console.log("caused by:", error.cause.message);
  console.log(error instanceof ConfigError, error instanceof Error);
}

How it works

  1. cause in the options records what went wrong underneath.
  2. Setting name makes the class readable in a log.
  3. Rethrow with context rather than swallowing.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
561
Tokens
145
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 2 of 2 in Errors, step 39 of 43 in Language basics.

← Previous Next →