Skip to content

Phase 8 / Task B2: Finding 021 — Validators throw EndpointError #177

Closed

Description

@Sam-Bolling

Phase 8 Task

Task ID: B2
Title: Finding 021 — Validators Throw EndpointError
Source: Senior dev code review #2
Severity: P2-Major (locked decision: EndpointError only, no subclass)
Category: Error Handling / API Design
Ownership: Ours (CSAPI module — csapi/helpers.ts + csapi/formats/**)
Phase 8 phase: B — API Surface Refinements


Goal

Every error a CSAPI consumer can catch on the URL-builder/parser surface is instanceof EndpointError. After this task, git grep -n "throw new Error\|throw new TypeError" -- src/ogc-api/csapi/ returns 0 matches. Consumer code using catch (e) { if (e instanceof EndpointError) ... } reliably narrows on every CSAPI failure mode.

Acceptance criterion (from P8-contribution-goal-and-definition.md): A4 — every CSAPI throw site emits EndpointError.

Locked Decision

⚠️ This decision is locked. Do not re-litigate in this issue. Surface deviations to the user; do not silently re-decide.

Decision (locked April 29, 2026): Option A — convert all plain throw new Error(...) / throw new TypeError(...) calls in CSAPI helpers and parsers to throw new EndpointError(...). No CSAPI-specific error subclass will be introduced.

Rationale:

  • EndpointError is the upstream-shipped public exception class (src/shared/errors.ts, exported from src/index.ts) already used by stac/, wmts/, and ogc-api/endpoint.ts. Consumers already write catch (e) { if (e instanceof EndpointError) ... }.
  • The reviewer's concern was that narrowing was unreliable, not that finer-grained types were missing. Standardizing on a single existing class fixes the narrowing complaint with no public-surface expansion.
  • EndpointError already carries httpStatus and isCrossOriginRelated, which covers every failure mode in the table.
  • Introducing CSAPIError extends EndpointError would be the first new public exception type added by the CSAPI work and would fail Phase 8's hard scope fence.

Option B (document the mixed contract instead of fixing it) is rejected April 29, 2026 — the reviewer's narrowing complaint remains valid.

Scope boundary: B2 covers helpers and parser-internal throws only. The factory try/catch that wraps network errors from OgcApiEndpoint is deferred to Task D1 (endpoint.csapi()), where the network awaits actually live after the 018+024 refactor. Do NOT add network-error wrapping in factory.ts here.

Locked in:


Problem Statement

The CSAPI module's error contract currently mixes three error types depending on failure mode:

Failure mode Error type Has httpStatus?
CSAPI not supported EndpointError No
Invalid collection document EndpointError No
Network failure (propagated from OgcApiEndpoint) TypeError No
Resource type unavailable EndpointError No
Invalid limit / bbox / datetime plain Error No
Malformed response body plain Error No

Consumer catch (e) { if (e instanceof EndpointError) ... } patterns work for some failure modes and silently miss others. Validators in helpers.ts and parsers in formats/ throw plain Error, breaking the narrowing.

Affected code (re-verify exact line numbers via git grep -n "throw new Error\|throw new TypeError" -- src/ogc-api/csapi/ immediately before editing — Phase 7 may have shifted lines):

  • src/ogc-api/csapi/helpers.ts — formatDateTimeParameter (~lines 47, 77), validateLimit (~lines 216, 234), validateBbox (~lines 240, 245, 248)
  • src/ogc-api/csapi/formats/response.ts — parseCollectionResponse (~lines 94, 106)
  • src/ogc-api/csapi/formats/part2.ts — requireObject (~line 48)
  • src/ogc-api/csapi/formats/property.ts — parseProperty (~line 42)
  • src/ogc-api/csapi/formats/schema-response.ts — (~lines 70, 150; re-verify)
  • src/ogc-api/csapi/formats/geojson.ts — (~lines 446, 453; re-verify)
  • src/ogc-api/csapi/formats/swecommon/_helpers.ts — (~line 75; re-verify)

The factory's TypeError propagation from endpoint.root / endpoint.getCollectionDocument is OUT OF SCOPE for B2. It is moved to D1, since after D1's refactor the network awaits live in OgcApiEndpoint.csapi(), not in createCSAPIBuilder.

Impact: Consumer narrowing fails silently for argument validation and parser failures. Pure DX/contract issue; no library-side runtime correctness bug.

Files to Modify

File Action Est. Lines Purpose
src/ogc-api/csapi/helpers.ts Modify ~10 Replace plain Error/TypeError throws with EndpointError; add import
src/ogc-api/csapi/formats/response.ts Modify ~5 Same
src/ogc-api/csapi/formats/part2.ts Modify ~3 Same
src/ogc-api/csapi/formats/property.ts Modify ~3 Same
src/ogc-api/csapi/formats/schema-response.ts Modify ~5 Same
src/ogc-api/csapi/formats/geojson.ts Modify ~5 Same
src/ogc-api/csapi/formats/swecommon/_helpers.ts Modify ~3 Same
src/ogc-api/csapi/helpers.spec.ts Modify ~10 Replace expect(...).toThrow(Error) with expect(...).toThrow(EndpointError)
src/ogc-api/csapi/url_builder.spec.ts Modify ~5 Same
src/ogc-api/csapi/factory.spec.ts Modify ~5 Same (parser-internal throw assertions only; factory network-wrap deferred to D1)
Other parser .spec.ts files (per re-verified grep) Modify ~10 Same

Cross-reference P8-implementation-guide §4.5 for the canonical files-modified list. If you find yourself adding a file that isn't in the implementation guide, stop — surface the question.

Implementation Approach

Pull the canonical pattern from P8-implementation-guide §4.5.

Step 1 — Re-verify exact lines (Phase 7 may have shifted them):

git grep -n "throw new Error\|throw new TypeError" -- src/ogc-api/csapi/

Adjust the file table above based on the live grep before editing. Do not blindly trust 021's snapshot.

Step 2 — Mechanical replacement pattern (apply to every grep hit):

+import { EndpointError } from '../../shared/errors.js'; // path varies per file

-throw new Error(`limit must be a positive integer, got ${value}`);
+throw new EndpointError(`limit must be a positive integer, got ${value}`);

Message text stays identical; only the constructor changes. Import path is relative to each file's location (e.g. ../../shared/errors.js from csapi/helpers.ts, ../../../shared/errors.js from csapi/formats/swecommon/_helpers.ts).

Step 3 — Update spec assertions:

-expect(() => validateLimit(-1)).toThrow(Error);
+expect(() => validateLimit(-1)).toThrow(EndpointError);

Add import { EndpointError } from '<correct-relative-path>'; to each spec file as needed. Because EndpointError extends Error, any pre-existing instanceof Error assertion still narrows; we tighten to EndpointError only where the spec already asserts a specific error type.

Step 4 — DO NOT touch createCSAPIBuilder in factory.ts. The factory wrapping try/catch for network errors is Task D1's job, since after D1's 018+024 refactor the awaits live in endpoint.csapi() rather than createCSAPIBuilder. Touching the factory here means re-doing the work in D1.

Test impact: Mechanical replacement of error-type assertions; no new test logic. The only new test in this task may be: a spec confirming validateLimit/validateBbox/formatDateTimeParameter throw an error that is instanceof EndpointError (one assertion per validator suffices; reuse existing test cases).

Scope — What NOT to Touch

Acceptance Criteria

  • Every plain throw new Error(...) / throw new TypeError(...) inside src/ogc-api/csapi/ (helpers + parsers) replaced with throw new EndpointError(...)
  • Error message text unchanged across the conversion (only the constructor changes)
  • EndpointError import added to every modified file at the correct relative path
  • Spec files updated: expect(...).toThrow(EndpointError) replaces expect(...).toThrow(Error) everywhere a specific error type is asserted
  • No try/catch wrapping added to createCSAPIBuilder in factory.ts (deferred to D1)
  • No CSAPIError subclass introduced
  • git grep -n "throw new Error\|throw new TypeError" -- src/ogc-api/csapi/ returns 0 matches
  • All modified files pass npx prettier --check
  • npm run typecheck exits 0
  • npm run lint exits 0
  • npm run test:browser exits 0
  • npm run test:node exits 0

Acceptance Gate (verification command)

The Phase 8 roadmap defines a specific verification command for this task (P8-ROADMAP §Phase B Task B2). Paste the output of these commands on the issue before closing:

# 1. Confirm zero plain Error/TypeError throws inside CSAPI
git grep -n "throw new Error\|throw new TypeError" -- src/ogc-api/csapi/
# Expected: zero matches

# 2. Confirm no CSAPIError subclass was introduced
git grep -n "class CSAPIError" -- src/
# Expected: zero matches

# 3. Confirm factory still does not wrap network errors (D1's job)
git grep -n "try" -- src/ogc-api/csapi/factory.ts
# Expected: zero try blocks (or whatever the pre-B2 baseline was — re-verify)

# 4. Full upstream QA suite (must mirror .github/workflows/qa.yml)
npm run format:check
npm run typecheck
npm run lint
npm run test:browser
npm run test:node

Expected output:

  • All three git grep commands return the expected zero/baseline matches
  • All five upstream QA commands exit 0

Dependencies

Mandatory. Walk the P8-ROADMAP dependency graph and fill in every applicable row.

Blocked by: Nothing within Phase 8
Blocks:

  • Task C1 (Issue Phase 8 / Task C1: Issue #166 — Part 2 @link fallback in cross-reference fields #166 — Part 2 @link fallback) — soft sequencing only. C1 was placed after B2 in the roadmap so any parser-internal throw it touches is already on the standardized EndpointError type, avoiding one round of revisit.
  • Task D1 (factory + endpoint refactor) — D1 builds the network-error try/catch in endpoint.csapi() on top of B2's already-standardized helper/parser throws. Without B2, D1 would have to either ship two PR-able units in one task or accept a temporarily inconsistent error contract mid-task.
    Related: Task B1 (independent rename; recommended sequencing puts B1 first because rename-symbol churn is easier to verify on a stable error-type baseline)

Roadmap dependency row: P8-ROADMAP §Phase B Task B2: "Effort: Mechanical (~2 hours; ~12 throw sites + spec updates). Risk: Low (EndpointError extends Error, so any existing instanceof Error assertion still narrows). Dependencies: None within Phase 8."

References

# Document What It Provides
1 P8-contribution-goal-and-definition.md Phase 8 goal, scope, acceptance criteria, locked decisions
2 P8-implementation-guide.md §4.5 Authoritative execution-level guide (this task)
3 P8-ROADMAP.md §Phase B Task B2 Task ordering, dependencies, acceptance gate
4 docs/code-review/021-pending-p2-validators-throw-plain-error.md Authoritative "why" + locked decision
5 src/shared/errors.ts EndpointError definition (do not touch)
6 src/ogc-api/csapi/helpers.ts + csapi/formats/** Receives the throw-site conversions
7 src/ogc-api/csapi/factory.ts DO NOT touch — network-wrapping is Task D1's job
8 All matching *.spec.ts files Receive expect(...).toThrow(EndpointError) updates

Activity

  1. Sam-Bolling commented on Apr 29, 2026

    @Sam-Bolling
    Author

    Workflow & Closing Step (applies to this issue)

    When working this issue, follow this workflow exactly:

    1. Check off the Acceptance Criteria checkboxes in this issue body as each item is satisfied — edit the issue body in place, do not just track the state externally.
    2. Commit and sync all changes from VS Code to the GitHub repository (git commit + git push origin <branch>). Verify with git status that the working tree is clean and git log origin/<branch>..HEAD is empty.
    3. Final step (mandatory): close this issue with a summary comment. The closing comment must contain at minimum:
      • The commit SHA(s) that satisfy this issue.
      • Confirmation that every Acceptance Criteria checkbox is now ticked in the body.
      • The acceptance-gate command output (or a one-line "all gates exit 0" with a link to the run, if applicable).
      • Any deviation from the locked decision (none expected).

    The issue is not complete until it has been closed with a summary comment per step 3. Closing-with-comment is part of the issue's own definition of done. Do not declare this task finished and do not move to the next task while this issue is still open.

    Acceptance-gate scrub: NO manual review

    Any prior wording in this issue body that asks for a "manual review confirmation paragraph", "manual review paragraph", "human review", or any other free-form prose-confirmation gate is rescinded. The acceptance gate is the set of automated commands listed under Acceptance Gate (verification command) — exit codes only, no manual-review prose. If any such manual-review wording appears in the original body of this issue, treat it as a no-op and ignore it.

    If the original verification block called for a "manual review confirmation" step, the corrected gate is:

    • All npx prettier --check invocations exit 0.
    • All npm run QA invocations (format:check, typecheck, lint, test:browser, test:node) exit 0.
    • Any browser-suite failures must be confirmed pre-existing on the parent baseline (phase-8 HEAD prior to this task's commit) — paste a one-line git stash; npx jest <suite>; git stash pop reproduction in the closing comment.

    For PR-page verification gates that previously called for "manual / browser" inspection of pull/136, replace with API-based verification using the GitHub MCP tools (mcp_io_github_git_pull_request_read, mcp_io_github_git_list_commits) — no browser, no manual screenshotting.

  2. Sam-Bolling commented on Apr 29, 2026

    @Sam-Bolling
    Author

    Task B2 complete — closed by commit addd048 on phase-8.

    What shipped

    Replaced every throw new Error(...) in the CSAPI URL-builder/parser surface with throw new EndpointError(...) so all consumer-catchable errors from this layer satisfy error instanceof EndpointError.

    Modules touched (7 source + 1 spec):

    • src/ogc-api/csapi/helpers.ts — 6 sites (formatDateTimeParameter, assertValidResourceType, validateLimit, validateBbox ×4)
    • src/ogc-api/csapi/formats/response.ts — 2 sites in parseCollectionResponse
    • src/ogc-api/csapi/formats/part2.ts — 1 site in requireObject (covers all 5 Part 2 parsers)
    • src/ogc-api/csapi/formats/property.ts — 1 site in parseProperty
    • src/ogc-api/csapi/formats/schema-response.ts — 2 sites
    • src/ogc-api/csapi/formats/geojson.ts — 2 sites in extractCSAPIFeature
    • src/ogc-api/csapi/formats/swecommon/_helpers.ts — 1 site in parseAssociationAttributeGroup
    • src/ogc-api/csapi/formats/geojson.spec.ts — assertion tightened .toThrow(Error) → .toThrow(EndpointError)

    JSDoc @throws tags updated in lockstep.

    Acceptance gate

    git grep 'throw new Error|throw new TypeError' -- src/ogc-api/csapi/ returns one match: a JSDoc @example in url_builder.ts L2671 showing consumer-side fetch handling (not a library throw site, intentionally left as-is).

    Validation

    Gate Result
    tsc --noEmit ✅ clean
    eslint ✅ clean
    prettier --check ✅ clean
    CSAPI suites (src/ogc-api/csapi) ✅ 30 suites / 1349 tests pass

    Scope boundary

    Factory-level wrapping of network-await throws in endpoint.csapi() is deferred to D1 / #179 by design — it lands with the coordinated 018+024 refactor (OgcApiEndpoint.root re-privatization + new value-shaped factory entry point). This task is strictly the validator/parser layer.

    Closes via Finding 021. No CSAPIError subclass introduced (per Phase 7 directive).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions