Skip to content

fix: throw on non-2xx HTTP status in fetchSpec and add unit tests#2104

Open
Adi-204 wants to merge 2 commits into
asyncapi:masterfrom
Adi-204:fix/fetch-spec-http-error-status
Open

fix: throw on non-2xx HTTP status in fetchSpec and add unit tests#2104
Adi-204 wants to merge 2 commits into
asyncapi:masterfrom
Adi-204:fix/fetch-spec-http-error-status

Conversation

@Adi-204
Copy link
Copy Markdown
Member

@Adi-204 Adi-204 commented May 25, 2026

Description

Fix fetchSpec silently resolving on non-2xx HTTP responses. Previously, fetching an AsyncAPI document from a URL that returned a 4xx or 5xx status would resolve with the error response body (e.g. an HTML page) instead of rejecting. fetchSpec now throws a descriptive error including the URL and HTTP status code, so failures are surfaced immediately rather than propagating as invalid spec content.

Related issue(s)
Fixes #1807

Summary by CodeRabbit

  • Bug Fixes

    • Improved HTTP response handling so non-2xx responses now produce descriptive errors (including request URL and status), preventing error responses from being treated as valid data.
  • Tests

    • Added tests covering successful responses and various HTTP error scenarios to verify error messages and handling.

Review Change Stack

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented May 25, 2026

🦋 Changeset detected

Latest commit: 2f632fc

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@asyncapi/generator Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@asyncapi-bot
Copy link
Copy Markdown
Contributor

What reviewer looks at during PR review

The following are ideal points maintainers look for during review. Reviewing these points yourself beforehand can help streamline the review process and reduce time to merge.

  1. PR Title: Use a concise title that follows our Conventional Commits guidelines and clearly summarizes the change using imperative mood (it means spoken or written as if giving a command or instruction, like "add new helper for listing operations")

    Note - In Generator, prepend feat: or fix: in PR title only when PATCH/MINOR release must be triggered.

  2. PR Description: Clearly explain the issue being solved, summarize the changes made, and mention the related issue.

    Note - In Generator, we use Maintainers Work board to track progress. Ensure the PR Description includes Resolves #<issue-number> or Fixes #<issue-number> this will automatically close the linked issue when the PR is merged and helps automate the maintainers workflow.

  3. Documentation: Update the relevant Generator documentation to accurately reflect the changes introduced in the PR, ensuring users and contributors have up-to-date guidance.

  4. Comments and JSDoc: Write clear and consistent JSDoc comments for functions, including parameter types, return values, and error conditions, so others can easily understand and use the code.

  5. DRY Code: Ensure the code follows the Don't Repeat Yourself principle. Look out for duplicate logic that can be reused.

  6. Test Coverage: Ensure the new code is well-tested with meaningful test cases that pass consistently and cover all relevant edge cases.

  7. Commit History: Contributors should avoid force-pushing as much as possible. It makes it harder to track incremental changes and review the latest updates.

  8. Template Design Principles Alignment: While reviewing template-related changes in the packages/ directory, ensure they align with the Assumptions and Principles. If any principle feels outdated or no longer applicable, start a discussion these principles are meant to evolve with the project.

  9. Reduce Scope When Needed: If an issue or PR feels too large or complex, consider splitting it and creating follow-up issues. Smaller, focused PRs are easier to review and merge.

  10. Bot Comments: As reviewers, check that contributors have appropriately addressed comments or suggestions made by automated bots. If there are bot comments the reviewer disagrees with, react to them or mark them as resolved, so the review history remains clear and accurate.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 25, 2026

Caution

Review failed

Failed to post review comments

📝 Walkthrough

Walkthrough

fetchSpec was refactored to use async/await, validate response.ok, and throw descriptive errors on non-2xx HTTP responses; tests and a Changeset entry were added to verify success and multiple failure scenarios.

Changes

fetchSpec HTTP Error Handling

Layer / File(s) Summary
fetchSpec HTTP error validation implementation
apps/generator/lib/utils.js
fetchSpec refactored to async/await with res.ok check that throws on non-2xx responses including URL and HTTP status. Minor whitespace formatting in registerTypeScript.
fetchSpec test suite and mock setup
apps/generator/test/utils.test.js
node-fetch mock configured for tests. New #fetchSpec test suite verifies successful resolution (HTTP 200) and rejection cases (404, 500, 503) with exact error message assertions.
Release notes for HTTP error fix
.changeset/fix-fetch-spec-http-error-status.md
Changeset documents that fetchSpec now throws on non-2xx HTTP responses and includes URL and status in the error message.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 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 PR title follows Conventional Commits with 'fix:' prefix and uses imperative mood to clearly summarize the main changes: throwing on non-2xx HTTP status in fetchSpec and adding unit tests.
Linked Issues check ✅ Passed The PR fully addresses #1807 by implementing immediate error rejection with clear messages including URL and HTTP status for non-2xx responses, and includes comprehensive unit tests.
Out of Scope Changes check ✅ Passed All changes are in-scope: refactoring fetchSpec to check res.ok and throw descriptive errors, adding unit tests, and a minor whitespace adjustment to registerTypeScript are all aligned with #1807 requirements.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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 and usage tips.

@sonarqubecloud
Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
B Maintainability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/generator/lib/utils.js (1)

62-68: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Add the @async tag to the JSDoc.

The function is now async, but the JSDoc is missing the @async tag. As per coding guidelines, public async functions should include the @async tag.

📝 Proposed fix to add `@async` tag
 /**
  * Fetches an AsyncAPI document from the given URL and return its content as string
  *
+ * `@async`
  * `@param` {String} link URL where the AsyncAPI document is located.
  * `@returns` {Promise<String>} Content of fetched file.
  * `@throws` {Error} When the HTTP response is not successful (non-2xx status).
  */
🤖 Prompt for 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.

In `@apps/generator/lib/utils.js` around lines 62 - 68, Add the missing `@async`
JSDoc tag to the docblock for the async function whose JSDoc begins "Fetches an
AsyncAPI document from the given URL and return its content as string" (the
async fetch function in utils.js), i.e., update that JSDoc to include an `@async`
tag along with the existing `@param`, `@returns`, and `@throws` entries so the public
async function follows the coding guidelines.
🧹 Nitpick comments (1)
apps/generator/lib/utils.js (1)

72-72: 💤 Low value

Consider simplifying the nested template literal.

The nested template literal reduces readability. You could extract the status text formatting to a variable for clarity.

♻️ Proposed refactor to improve readability
 utils.fetchSpec = async (link) => {
   const res = await fetch(link);
   if (!res.ok) {
-    throw new Error(`Failed to fetch AsyncAPI document from ${link}: HTTP ${res.status}${res.statusText ? ` ${res.statusText}` : ''}`);
+    const statusText = res.statusText ? ` ${res.statusText}` : '';
+    throw new Error(`Failed to fetch AsyncAPI document from ${link}: HTTP ${res.status}${statusText}`);
   }
   return res.text();
 };

As per coding guidelines, static analysis flagged this as a code smell for nested template literals.

🤖 Prompt for 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.

In `@apps/generator/lib/utils.js` at line 72, Extract the status-text fragment
into a local variable and use that variable in the Error message to avoid the
nested template literal; specifically, in the throw new Error statement that
builds the message with link, res.status and res.statusText, create a const
(e.g. statusText or formattedStatusText) that computes res.statusText ? `
${res.statusText}` : '' and then interpolate that variable into the final
template literal so the throw new Error uses `Failed to fetch AsyncAPI document
from ${link}: HTTP ${res.status}${statusText}` for improved readability.
🤖 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.

Outside diff comments:
In `@apps/generator/lib/utils.js`:
- Around line 62-68: Add the missing `@async` JSDoc tag to the docblock for the
async function whose JSDoc begins "Fetches an AsyncAPI document from the given
URL and return its content as string" (the async fetch function in utils.js),
i.e., update that JSDoc to include an `@async` tag along with the existing `@param`,
`@returns`, and `@throws` entries so the public async function follows the coding
guidelines.

---

Nitpick comments:
In `@apps/generator/lib/utils.js`:
- Line 72: Extract the status-text fragment into a local variable and use that
variable in the Error message to avoid the nested template literal;
specifically, in the throw new Error statement that builds the message with
link, res.status and res.statusText, create a const (e.g. statusText or
formattedStatusText) that computes res.statusText ? ` ${res.statusText}` : ''
and then interpolate that variable into the final template literal so the throw
new Error uses `Failed to fetch AsyncAPI document from ${link}: HTTP
${res.status}${statusText}` for improved readability.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: bded0fe7-0a49-412f-a325-fcc0e6033b0d

📥 Commits

Reviewing files that changed from the base of the PR and between 917a555 and a371399.

📒 Files selected for processing (3)
  • .changeset/fix-fetch-spec-http-error-status.md
  • apps/generator/lib/utils.js
  • apps/generator/test/utils.test.js

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.

[BUG] fetchSpec doesn't handle HTTP error status codes

2 participants