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/errorbash
pnpm add @rcompat/errorbash
yarn add @rcompat/errorbash
bun add @rcompat/errorUsage#
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"); // trueError 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"