Skip to content

fix: make ctx.assert errors instanceof HttpError - #1998

Open
yowainwright wants to merge 1 commit into
masterfrom
fix/ctx-assert-http-error-instanceof
Open

fix: make ctx.assert errors instanceof HttpError#1998
yowainwright wants to merge 1 commit into
masterfrom
fix/ctx-assert-http-error-instanceof

Conversation

@yowainwright

@yowainwright yowainwright commented Aug 25, 2026

Copy link
Copy Markdown
Member

Human Summary

ctx.assert() errors pass Koa.isHttpError(err) but fail err instanceof Koa.HttpError because they come from http-assert's nested http-errors.

This wraps http-assert failures with Koa's http-errors while keeping the existing assertion behavior.

Approach comparisons

I took 2 routes and landed on the last version b/c of lack of risk and readability

  1. current buggy version
  2. easier to look at, but mutations posed risk
  3. gross-looking but very procedural function; no wrapping
Approach Pros Cons Regression risk Evidence
Master: export root http-errors HttpError; leave ctx.assert as http-assert Smallest code surface; preserves upstream http-assert behavior exactly ctx.assert() errors fail err instanceof Koa.HttpError when http-assert uses a nested http-errors copy Existing bug remains ctx.assert delegates to http-assert; Koa exports root createHttpError.HttpError
First PR version: wrap ctx.assert; rebuild failures with root http-errors Makes direct and named ctx.assert failures pass instanceof Koa.HttpError; status-specific Koa constructors can match Replaces the thrown error; Object.assign({}, err) copies only enumerable own properties; stack, descriptors, symbols, and identity can change Highest: callers can observe a different error object shape http-assert throws createError(status, msg, opts); http-errors creates or mutates error fields based on its own status parsing
Current version: keep ctx.assert; add duck-typed Symbol.hasInstance to Koa.HttpError Does not wrap, replace, copy, or mutate ctx.assert() errors; keeps original constructor, stack, own props, and nested http-errors instanceof; fixes err instanceof Koa.HttpError Broadens Koa.HttpError instanceof semantics from prototype-only to HTTP-error-shaped values; does not make errors instances of Koa's status-specific constructors Lower: changes only the public base-class check, not thrown error shape Mirrors http-errors.isHttpError duck-typing fallback: Error, boolean expose, numeric statusCode, and matching status

Summary by Sourcery

Make ctx.assert() failures compatible with Koa’s HTTP error type checks.

Bug Fixes:

  • Make errors thrown by ctx.assert() and its named assertion methods recognize as Koa.HttpError instances while preserving their existing status, messages, and custom properties.

Enhancements:

  • Add coverage for HTTP error identity, propagated error details, custom options, and successful assertions.

Summary by CodeRabbit

  • Bug Fixes

    • Improved HTTP error recognition so matching errors are correctly identified across contexts.
    • Preserved original HTTP error types and metadata when using assertion helpers.
    • Ensured custom error options remain available for more reliable error handling.
  • Tests

    • Added coverage for HTTP error identity, custom options, truthy assertions, and named assertion methods.

@coderabbitai

coderabbitai Bot commented Aug 25, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4a8249c0-a58c-4670-8082-944918ee8cf6

📥 Commits

Reviewing files that changed from the base of the PR and between af0153a and a21ca97.

📒 Files selected for processing (1)
  • lib/application.js

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Koa now uses structural HttpError detection for instanceof HttpError checks. Tests cover ctx.assert error identity, constructors, status metadata, custom options, truthy values, and named assertion methods.

Suggested reviewers: nuintun

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 3 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes satisfy issue #1925. lib/application.js adds structural HttpError detection through Symbol.hasInstance, and the new tests verify that ctx.assert errors preserve their identity while passin…
Out of Scope Changes check ✅ Passed The changes are limited to the requested HttpError behavior and its tests. No unrelated code changes are present.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: making errors from ctx.assert satisfy instanceof HttpError.
Full details: Linked Issues check

Explanation

The changes satisfy issue #1925. lib/application.js adds structural HttpError detection through Symbol.hasInstance, and the new tests verify that ctx.assert errors preserve their identity while passing instanceof HttpError checks and retaining specific error behavior.

  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Aug 25, 2026

Copy link
Copy Markdown

Reviewer's Guide

Updates Koa's HTTP error identity semantics so ctx.assert failures from nested http-errors are recognized as Koa.HttpError instances while preserving the original error type, assertion behavior, and metadata; adds comprehensive regression tests.

Sequence diagram for ctx.assert HTTP error identity

sequenceDiagram
    participant Caller
    participant Context
    participant HttpAssert
    participant HttpError
    Caller->>Context: assert(condition, status, message, options)
    Context->>HttpAssert: assert(condition, status, message, options)
    HttpAssert-->>Context: nested HttpError
    Context->>HttpError: HttpError[Symbol.hasInstance](error)
    HttpError-->>Caller: true for HTTP-error-like error
Loading

File-Level Changes

Change Details Files
Broaden Koa HTTP error identity checks to recognize compatible errors from nested http-errors dependencies.
  • Define an HttpError Symbol.hasInstance predicate based on Error status and expose properties.
  • Allow ctx.assert and its named assertion methods to satisfy instanceof Koa.HttpError without changing their original constructors or behavior.
lib/application.js
Add regression coverage for assertion error identity and preserved metadata.
  • Verify status, statusCode, message, expose, custom options, and compatibility with both Koa and nested http-errors checks.
  • Cover all named assertion methods and successful truthy assertions.
__tests__/context/assert.test.js

Assessment against linked issues

Issue Objective Addressed Explanation
#1925 Make errors thrown by ctx.assert() pass instanceof Koa.HttpError checks, including errors produced by its named assertion methods.
#1925 Preserve the existing ctx.assert() behavior and HTTP error properties, including the specific error class, status, message, expose flag, and custom options.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Aug 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.90%. Comparing base (4a191b1) to head (a21ca97).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1998   +/-   ##
=======================================
  Coverage   99.90%   99.90%           
=======================================
  Files           9        9           
  Lines        2110     2125   +15     
=======================================
+ Hits         2108     2123   +15     
  Misses          2        2           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've reviewed your changes and they look great!

Sourcery assessment

Approved.


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@yowainwright
yowainwright force-pushed the fix/ctx-assert-http-error-instanceof branch from 0be5fa7 to 94e60bd Compare August 25, 2026 07:16
@yowainwright

Copy link
Copy Markdown
Member Author

cr plz @jonathanong @fengmk2 @3imed-jaberi

@yowainwright
yowainwright force-pushed the fix/ctx-assert-http-error-instanceof branch from af0153a to 3161670 Compare August 26, 2026 01:32
@yowainwright

Copy link
Copy Markdown
Member Author

@sourcery-ai re-review

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've reviewed your changes and they look great!

Sourcery assessment

Approved.


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@sourcery-ai

sourcery-ai Bot commented Aug 26, 2026

Copy link
Copy Markdown

Hey @yowainwright, I've posted a new review for you!

@yowainwright
yowainwright force-pushed the fix/ctx-assert-http-error-instanceof branch 2 times, most recently from befc3bf to 7d41da9 Compare August 26, 2026 03:19
@yowainwright
yowainwright force-pushed the fix/ctx-assert-http-error-instanceof branch from 7d41da9 to a21ca97 Compare August 26, 2026 03:22
@koajs koajs deleted a comment from sourcery-ai Bot Aug 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[fix] ctx.assert() throws specific error classes

1 participant