Skip to content

fix(har): guard HAR logging when a request matches no mock [RQ-2398] - #40

Open
dinex-dev wants to merge 2 commits into
masterfrom
fix/har-unmatched-request-guard
Open

fix(har): guard HAR logging when a request matches no mock [RQ-2398]#40
dinex-dev wants to merge 2 commits into
masterfrom
fix/har-unmatched-request-guard

Conversation

@dinex-dev

@dinex-dev dinex-dev commented Jul 30, 2026

Copy link
Copy Markdown
Member

Problem

The HAR logging middleware registers a res.once('finish', …) handler that reads res.locals.rq_metadata.mockId. rq_metadata is only populated for requests that resolve to a mock — for any unmatched request (e.g. a 404), it is undefined, and the access throws TypeError: Cannot read properties of undefined (reading 'mockId').

Because the throw happens inside the finish event callback (after the response is sent, outside the Express request/error pipeline), it isn't caught as a normal request error. It also means unmatched requests fail before any logging runs.

Fix

  • Access the id with optional chaining and bail out early when there is no mockId — an unmatched request has no mock to associate a log with.
  • Wrap the handler body in try/catch so any logging error is logged and contained instead of propagating out of the event callback.

No behavior change for matched requests: they still log exactly as before.

Testing

  • npm run build (tsc) passes.
  • Simulated the finish handler for both paths:
    • unmatched request (no rq_metadata) → no throw, logging skipped;
    • matched request → logs once with the correct mockId and a populated HAR entry.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability when recording HAR logs by preventing logging errors from causing uncaught exceptions.
    • Safely handles responses without an associated mock identifier, such as 404 responses.
    • Reports failures to store HAR logs without disrupting the response lifecycle.

The HAR middleware's `finish` listener read `res.locals.rq_metadata.mockId`
unconditionally. For requests that don't match any mock, `rq_metadata` is
undefined, so this threw a `TypeError` inside the `finish` event callback —
outside Express's request-handling context, where it surfaces as an uncaught
exception rather than a handled request error.

- Read the id via optional chaining (`res.locals.rq_metadata?.mockId`).
- Skip logging when there is no `mockId`; an unmatched request has no mock to
  attach the log to (and the downstream sink keys logs by mockId).
- Wrap the callback in try/catch so a logging failure can never escape the
  finish handler.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@dinex-dev, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 40 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d854355e-9dc7-42ce-aa84-1fe62047a570

📥 Commits

Reviewing files that changed from the base of the PR and between f621659 and 6f3f3a0.

📒 Files selected for processing (1)
  • src/middlewares/har.ts

Walkthrough

HarMiddleware now safely handles response completion by reading mockId optionally, skipping HAR log storage when it is absent, and catching errors during HAR entry creation or storage. Storage failures are reported with console.error.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: guarding HAR logging for unmatched requests.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/har-unmatched-request-guard

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.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/middlewares/har.ts`:
- Line 35: Update the finish callback containing storageService.storeLog to
handle the returned Promise rejection: make the callback async and await
storeLog, or attach an equivalent catch handler so failures are processed by the
existing error path instead of becoming unhandled rejections.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a3dd4eb5-751c-44c8-8f8e-63cf7dbde116

📥 Commits

Reviewing files that changed from the base of the PR and between c8ca449 and f621659.

📒 Files selected for processing (1)
  • src/middlewares/har.ts

Comment thread src/middlewares/har.ts Outdated
storageService.storeLog returns a Promise, so the synchronous try/catch did
not cover a rejection from the sink's sendLog — it would surface as an
unhandled rejection. Make the finish callback async and await the call so the
rejection lands in the existing catch.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
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.

1 participant