@asaidimu/utils-error
v1.1.11
Published
A collection of error utilities.
Readme
@asaidimu/utils-error
Structured error codes and a traceable SystemError for TypeScript applications: every failure carries a stable code, category, HTTP status, log level, and suggested action — plus a flat, chronological trace of its root causes.
Table of Contents
- Features
- Installation
- Quick Start
- Concepts
- Usage
- Built-in Error Codes
- API Reference
- Development & Testing
- License
Features
- Stable, documented codes –
CATEGORY-XXX[-SUFFIX]identifiers (VAL-001,SYNC-002-DUP,AUTH-001-DENIED) shared across services and safe to switch on. - Metadata registry – each code resolves to a
description,category,httpStatus,logLevel, and suggestedaction. SystemError– anErrorsubclass that keepscode,severity,path,operation,issues,cause, andtimestamp.- Immutable builders –
withPath(),withOperation(),withIssue(s)(), andwithCause()return new instances instead of mutating. - Chronological traces –
toJSON()flattens deep cause chains into a root-firsttracearray;AggregateErrorbecomes a parallel branch group. - Runtime extensibility –
registerErrorCode()adds project-specific codes with full metadata. Result<T, E>– a small ok/fail union for functions that prefer returning errors over throwing.- Zero dependencies – plain TypeScript, tree-shakeable named exports.
Installation
npm install @asaidimu/utils-error
# or
bun add @asaidimu/utils-errorInside this monorepo the same module is imported as @core/error (see tsconfig.json paths).
Quick Start
import { SystemError, ErrorCodes, Errors } from "@asaidimu/utils-error";
throw Errors.notFound("users.42", "user 42 does not exist");
// or construct explicitly:
const err = new SystemError({
code: ErrorCodes.VALIDATION_FAILED.code, // "VAL-001"
message: "profile payload rejected",
path: "users.0.email",
operation: "user:update",
issues: [{ code: "REQUIRED_FIELD_MISSING", message: "email is required" }],
});
err.getHttpStatus(); // 400
err.toString();
// [VAL-001] profile payload rejected (validation) at 'users.0.email' during 'user:update'
// Issues:
// 1. email is required [REQUIRED_FIELD_MISSING]If message is omitted, the code's registered description is used, so errors are informative even when you add no text.
Concepts
Error codes
A code is a string like SYNC-002-DUP. getErrorMetadata(code) returns its ErrorCodeMetadata:
| Field | Meaning |
| ------------- | -------------------------------------------------------------------------------------------------------- |
| code | Formal identifier, e.g. "VAL-001" |
| name | Uppercase type name, e.g. "VALIDATION_FAILED" |
| description | When/why the error occurs (also the default message) |
| category | validation | database | auth | business | system | network | concurrency | custom |
| httpStatus | Suggested HTTP status for REST responses |
| logLevel | Recommended logging threshold: debug | info | warn | error |
| action | Optional suggested remediation step |
Lookup order: built-in registry → your runtime registrations → a generic custom fallback (httpStatus: 500, description "Unknown error: <code>"). isKnownErrorCode(code) tells you whether the first two matched.
SystemError
new SystemError({
code, // required — registered code
message?, // defaults to the code's description
severity?, // "error" (default) | "warning" | "info"
path?, // document/state path, e.g. "users.0.email"
operation?, // function/step that was executing
issues?, // readonly Issue[]
cause?, // Error | unknown | unknown[] (concurrent branches)
metadata?, // Partial<ErrorCodeMetadata> override (code/category are fixed)
});codeMetadata is the merged metadata actually used by this instance, so a single error can override httpStatus or action without re-registering the code.
Issues
Issue describes a concrete validation/operational problem, and can nest:
interface Issue {
code: string; // "REQUIRED_FIELD_MISSING"
message: string;
path?: string; // "users.0.email"
index?: number; // element index for arrays
severity?: "error" | "warning" | "info";
description?: string;
cause?: readonly Issue[];
}Traces
toJSON() / toLogEntry() walk cause chains and emit a flat, root-first array:
- the innermost/original failure first,
- each wrapper after it,
- the surface error last.
Parallel failures (AggregateError or an Error[] cause) become one { type: "parallel", tracks: [...] } node, each track being its own chronological sequence. Frames carry { operation, message, code?, category? }.
Usage
Creating errors
import {
SystemError,
ErrorCodes,
CommonErrors,
Errors,
createError,
error,
} from "@asaidimu/utils-error";
// Shorthand factories with sensible defaults
Errors.notFound("orders.7"); // SYNC-001-NF, path = "orders.7"
Errors.duplicateKey("users"); // SYNC-002-DUP
Errors.permissionDenied("invoice:write"); // AUTH-001-DENIED, operation set
Errors.validationFailed(issues, "users.0"); // VAL-001 + issues
Errors.internalError(cause); // SYS-001 + cause
// Generic factories
createError(CommonErrors.BACKEND_ERROR, "payments gateway is down");
error(CommonErrors.INTERNAL_ERROR); // identical to createError
// Direct construction with full context
new SystemError({
code: ErrorCodes.STALE_VERSION_MISMATCH.code,
severity: "warning",
metadata: { httpStatus: 412, action: "reload and reapply the change" },
});CommonErrors exposes the same codes as plain strings when you do not want to touch the metadata objects.
Annotating immutably
Every withX() returns a new SystemError; the original is untouched:
const base = new SystemError({ code: "SYS-001", message: "run failed" });
const located = base
.withPath("workflows.3.nodes.12")
.withOperation("node:run")
.withIssue({ code: "TIMEOUT", message: "node exceeded 30s budget" })
.withCause(new Error("socket hang up"));
base.path; // undefined
located.path; // "workflows.3.nodes.12"Serializing for logs and APIs
const payload = surfaceError.toLogEntry();
payload.httpStatus; // status to return upstream
payload.action; // remediation hint for operators
payload.trace; // root-first frames, surface error last
JSON.stringify(surfaceError); // uses toJSON() automaticallytoLogEntry() is an alias of toJSON() intended for ingestion pipelines. For terminals, toString() renders a compact multi-line dump:
[SYNC-003-LOCK] The resource is currently locked by another operation (database) at 'orders.1' during 'order:checkout'
Issues:
1. stock reserved elsewhere [STOCK_RESERVED]Registering custom codes
import { registerErrorCode, getErrorMetadata } from "@asaidimu/utils-error";
registerErrorCode({
code: "PAY-001-DECLINED",
name: "PAYMENT_DECLINED",
description: "The payment provider declined the charge",
category: "business",
httpStatus: 402,
logLevel: "warn",
action: "Ask the customer for a different payment method",
});
new SystemError({ code: "PAY-001-DECLINED" }); // full metadata, no fallbackRegistration throws if the code collides with a built-in or an already-registered custom code. It is idempotent only for your own code — pick unique prefixes per domain.
Wrapping foreign errors
import { errorFrom } from "@asaidimu/utils-error";
errorFrom(mySystemError); // returned as-is
errorFrom(new TypeError("boom")); // → SystemError with code "TypeError"
errorFrom(JSON.parse(serialized)); // reconstructs a persisted SystemError
errorFrom("anything else"); // → SYS-001 INTERNAL_ERROR with cause preservedThe Result type
import { Result } from "@asaidimu/utils-error";
function findUser(id: string) {
if (!id) return Result.fail(Errors.notFound("users"), { tookMs: 3 });
return Result.ok({ id }, { tookMs: 3 });
}
const res = findUser("u1");
if (res.ok) {
res.value; // { id: "u1" }
} else {
res.error; // SystemError
}
res.metadata; // optional shared metadata on both branchesBuilt-in Error Codes
All codes are exported via ErrorCodes (metadata objects) and selected ones via CommonErrors (strings).
| Code | Name | Category | HTTP |
| ----------------- | ---------------------------------- | ----------- | ---- |
| VAL-001 | VALIDATION_FAILED | validation | 400 |
| VAL-002 | REQUIRED_FIELD_MISSING | validation | 400 |
| VAL-003 | INVALID_FORMAT | validation | 400 |
| SYNC-001-NF | NOT_FOUND | database | 404 |
| SYNC-002-DUP | DUPLICATE_KEY | database | 409 |
| SYNC-003-LOCK | RESOURCE_LOCKED | database | 409 |
| SYNC-004-REL | RESOURCE_RELEASED | database | 410 |
| AUTH-001-DENIED | PERMISSION_DENIED | auth | 403 |
| AUTH-002-UNAUTH | UNAUTHENTICATED | auth | 401 |
| BUS-001 | INVALID_COMMAND | business | 400 |
| BUS-002-ABORT | OPERATION_ABORTED | business | 409 |
| SYS-001 | INTERNAL_ERROR | system | 500 |
| SYS-002 | BACKEND_ERROR | system | 502 |
| CON-001 | CONCURRENCY_ERROR | concurrency | 409 |
| SYNC-005-DDL | DEADLOCK_DETECTED | concurrency | 409 |
| SYNC-006-LTO | LOCK_ACQUISITION_TIMEOUT | concurrency | 408 |
| SYNC-007-SER | SERIALIZATION_FAILURE | concurrency | 409 |
| SYNC-008-WSK | WRITE_SKEW_DETECTED | concurrency | 409 |
| SYNC-009-RSK | READ_SKEW_DETECTED | concurrency | 409 |
| SYNC-010-PHR | PHANTOM_READ_DETECTED | concurrency | 409 |
| SYNC-011-STV | STALE_VERSION_MISMATCH | concurrency | 412 |
| SYNC-012-CMD | CONCURRENT_MODIFICATION_DETECTED | concurrency | 409 |
| SYNC-013-TIP | TRANSITION_IN_PROGRESS | concurrency | 423 |
| SYNC-014-AIS | ALREADY_IN_TARGET_STATE | concurrency | 200 |
| SYNC-015-CPE | CONNECTION_POOL_EXHAUSTED | concurrency | 503 |
| SYNC-016-TTE | TRANSACTION_EXPIRED | concurrency | 408 |
SYNC-001–SYNC-004also describe concurrency races (TOCTOU, duplicate insert, contention) insync_errors.ts; the database-framed metadata inerror.tswins for those four codes.SYNC-005–SYNC-016are concurrency-only. Each entry carries its owndescriptionandaction— read them viagetErrorMetadata(code)rather than memorising this table.
Packages in this monorepo may register additional groups on import — e.g. @asaidimu/utils-version registers VER-001–VER-011. Importing a package is enough to make its codes resolvable.
API Reference
| Export | Description |
| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| SystemError | Structured error with immutable builders and trace serialization |
| ErrorCodes | Registry of built-in code metadata |
| CommonErrors | The same built-in codes as plain strings |
| Errors | Factories: notFound, duplicateKey, permissionDenied, validationFailed, internalError |
| createError / error | new SystemError({ code, message }) shortcuts |
| errorFrom(value) | Coerce any thrown value into a SystemError |
| registerErrorCode(meta) | Register a custom code at runtime (throws on conflict) |
| getErrorMetadata(code) | Metadata lookup with graceful unknown-code fallback |
| isKnownErrorCode(code) | Whether a code is built-in or registered |
| Result | Result.ok(value, meta?) / Result.fail(err, meta?) union helpers |
| Severity, Issue | Validation/operational problem types |
| ErrorCodeMetadata | Shape of the code registry entries |
| ErrorCategory | Union of the eight categories |
| SystemErrorParams | Constructor options for SystemError |
| TraceFrame, TraceNode, ParallelTrace, ChronologicalTrace | Trace payload types |
Development & Testing
git clone https://github.com/asaidimu/erp-utils.git
cd erp-utils/src/error
bun install| Command | Description |
| ---------------------- | ---------------------------------- |
| npm test | Run the Vitest suite once |
| npm run test:watch | Run tests in watch mode |
| npm run test:browser | Run tests in a browser environment |
The suite covers metadata lookups, custom registration conflicts, immutable builders, JSON/trace serialization (including AggregateError parallel tracks), factories, and the Result type.
License
MIT © Saidimu
