Browse packages

Package · v0.12.0 · changelog

error

Standard library errors

Runtime support

  • Node
  • Deno
  • Bun
  • Browser

This module creates structured errors from tagged templates while preserving their strings and interpolated values. Stable string codes support matching across package and realm boundaries.

Installation#

bash
npm install @rcompat/error
bash
pnpm add @rcompat/error
bash
yarn add @rcompat/error
bash
bun add @rcompat/error

Usage#

Template errors#

Use error.template as a tagged template to retain both the rendered message and its original values:

js
import error from "@rcompat/error";

const filename = "config.json";
const failure = error.template`Could not read ${filename}`;

failure.message; // "Could not read config.json"
failure.strings; // ["Could not read ", ""]
failure.params; // ["config.json"]

Coded errors#

error.coded wraps an object of error factories. Each returned error carries the factory key as its stable code:

js
import error from "@rcompat/error";

const errors = error.coded({
  missing: name => error.template`Missing ${name}`,
  invalid: name => error.template`Invalid ${name}`,
});

const failure = errors.missing("token");

failure.code; // "missing"
error.CodeError.is(failure); // true
error.CodeError.matches(failure, "missing"); // true

Error names#

error.names creates a typed key-to-name object for sharing error codes without repeating string literals:

ts
import error from "@rcompat/error";

const names = error.names({
  missing: null,
  invalid: null,
});

names.missing; // "missing"
names.invalid; // "invalid"