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#
npm install @rcompat/errorpnpm add @rcompat/erroryarn add @rcompat/errorbun add @rcompat/errorUsage#
Template errors#
Use error.template as a tagged template to retain both the rendered message
and its original values:
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:
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:
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.