Files
skills/docs/foundation/data/json/src/errors/json-error.md
2026-05-29 08:20:56 +01:00

2.9 KiB

json-error

(no submodules)

Purpose

Provides the typed error class and stable code registry for @suaveplan/json. All error conditions produced by this package surface as JsonError instances with machine-readable codes so callers can branch on failure mode without parsing message strings.

Features

  • JSON_CODES registry — four stable codes under the JSON.* namespace
  • JsonCode union type for compile-time exhaustiveness checks
  • JsonError extends SuaveplanError — carries code, cause, and optional context payload; integrates with the OTel span-event adapter from @suaveplan/error

Usage: Basic Example

import { JsonError, JSON_CODES } from "@suaveplan/json/errors";

throw new JsonError(
  JSON_CODES["PARSE.FAILED"],
  "Unexpected token at position 0"
);

Usage: Advanced Example

import { JsonError, JSON_CODES } from "@suaveplan/json/errors";

function parseSafe(text: string): unknown {
  try {
    return JSON.parse(text);
  } catch (cause) {
    throw new JsonError(
      JSON_CODES["PARSE.FAILED"],
      `JSON parse failed: ${(cause as Error).message}`,
      { cause }
    );
  }
}

API Reference

JSON_CODES

const JSON_CODES: {
  "PARSE.FAILED": "JSON/PARSE.FAILED";
  "PARSE.PROTOTYPE_POLLUTION": "JSON/PARSE.PROTOTYPE_POLLUTION";
  "STRINGIFY.CIRCULAR": "JSON/STRINGIFY.CIRCULAR";
  "STRINGIFY.FAILED": "JSON/STRINGIFY.FAILED";
};

Stable, namespaced error codes produced by defineCodes("JSON", [...]). Each code is a string literal of the form "JSON/<segment>".

JsonCode

type JsonCode = (typeof JSON_CODES)[keyof typeof JSON_CODES];

Union of all four code literals. Use this type for exhaustive switch statements or discriminated-union handlers.

class JsonError

class JsonError extends SuaveplanError<JsonCode> {
  constructor(code: JsonCode, message: string, options?: SuaveplanErrorOptions);
}

Parameters

Parameter Type Description
code JsonCode Machine-readable error code from JSON_CODES.
message string Human-readable description of the error.
options SuaveplanErrorOptions? Optional cause, context, and meta fields.

Throws — never; constructor only constructs.

Implementation Notes

The constructor is flagged with // biome-ignore lint/complexity/noUselessConstructor because it widens the visibility of the SuaveplanError constructor from protected to public. This is required by the Biome linter which otherwise flags it as a no-op, but the widening is intentional and load-bearing.

Error codes are registered once at module load time via defineCodes. The defineCodes helper from @suaveplan/error is idempotent within a process (same namespace + same codes → same object reference), making it safe to import across multiple entry points without duplication.