npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@asaidimu/utils-error

v1.1.11

Published

A collection of error utilities.

Readme

@asaidimu/utils-error

TypeScript MIT License npm version

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

  • 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 suggested action.
  • SystemError – an Error subclass that keeps code, severity, path, operation, issues, cause, and timestamp.
  • Immutable builders – withPath(), withOperation(), withIssue(s)(), and withCause() return new instances instead of mutating.
  • Chronological traces – toJSON() flattens deep cause chains into a root-first trace array; AggregateError becomes 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-error

Inside 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:

  1. the innermost/original failure first,
  2. each wrapper after it,
  3. 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() automatically

toLogEntry() 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 fallback

Registration 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 preserved

The 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 branches

Built-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-004 also describe concurrency races (TOCTOU, duplicate insert, contention) in sync_errors.ts; the database-framed metadata in error.ts wins for those four codes. SYNC-005–SYNC-016 are concurrency-only. Each entry carries its own description and action — read them via getErrorMetadata(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