Browse packages

Package · v0.9.0

error

Standard library errors

Structured, portable errors for JavaScript runtimes.

What is @rcompat/error?#

@rcompat/error creates errors from tagged templates while preserving the template strings and interpolated values. It also provides stable string error codes that can be matched across package or realm boundaries. The same API works in Node, Bun, and Deno.

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"

API reference#

error.template(strings, ...params)#

Returns an Error with message, strings, and params properties.

error.coded(factories)#

Returns factories with the same keys and call signatures. Their errors are CodeError instances whose code is the corresponding factory key.

error.names(object)#

Returns an object that maps every input key to its own name.

error.CodeError#

Extends the template error with a code property. Use error.CodeError.is(value) to identify coded errors and error.CodeError.matches(value, code) to narrow a specific code. CodeError and TemplateError remain available as named type-only exports.