@domain-first/errors
v4.0.3
Published
Strongly typed namespace-based domain errors that remain identifiable across application boundaries
Maintainers
Readme
Installation
npm i @domain-first/errorsMotivation
In Domain-Driven Design, domain errors are part of the domain model, yet they are often treated as generic exceptions or untyped payloads. Serialized native Error objects lose their runtime identity after crossing process boundaries, making instanceof unusable after serialization. Domain-First Errors let you define strongly typed domain errors that remain identifiable both as runtime instances and as serialized objects.
Quick Start
import { errorNamespace } from "@domain-first/errors";
const UserErrors = errorNamespace("USER");
const AuthErrors = UserErrors.subnamespace("AUTH");
// Define an error class
const IncorrectPasswordError = AuthErrors.define<{
login: string;
}>("INCORRECT_PASSWORD");
// Throw and identify it
try {
throw new IncorrectPasswordError(
{ login: "test-login" },
// native Error.cause support
{ cause: 42 },
);
} catch (e: unknown) {
/**
USER.AUTH.INCORRECT_PASSWORD: {"login":"test-login"}
...stack
details: { login: 'test-login' },
code: 'USER.AUTH.INCORRECT_PASSWORD',
metadata: {},
[cause]: 42
}
*/
console.error(e);
// if (e instanceof IncorrectPasswordError) works as well
if (IncorrectPasswordError.is(e)) {
console.log(`Incorrect password (${e.details.login})`);
}
}
// Recognize a serialized error
const error = new IncorrectPasswordError({
login: "test-login",
});
const serializedError = JSON.parse(JSON.stringify(error.serialized));
if (IncorrectPasswordError.matchesCode(serializedError)) {
console.log("Incorrect password");
}About
A utility for defining strongly typed namespace-based domain errors with stable identities across application boundaries. Every defined error extends the native Error class and supports the native Error.cause property.
This makes errors easy to serialize, transport between layers, and recognize. Every error class provides two ways to identify that error type:
isfor runtime instances (instanceofworks as well);matchesCodefor serialized or transported errors.
Test coverage
Will be improved in upcoming versions.
| Type | Threshold | Current value | | ---------- | --------- | ------------- | | Statements | 80 % | 83.05 % | | Branches | 60 % | 64.1 % | | Functions | 85 % | 85.71 % | | Lines | 80 % | 82.14 % |
