Skip to content

fix(portal-sdk): handle empty responses and JSON parsing errors in AccountApi#452

Merged
pcfreak30 merged 1 commit intodevelopfrom
libs/portal-sdk
Aug 17, 2025
Merged

fix(portal-sdk): handle empty responses and JSON parsing errors in AccountApi#452
pcfreak30 merged 1 commit intodevelopfrom
libs/portal-sdk

Conversation

@pcfreak30
Copy link
Copy Markdown
Member

@pcfreak30 pcfreak30 commented Aug 17, 2025

  • Added check for empty responses (content-length=0 or status 204)
  • Added try-catch block for JSON parsing
  • Return undefined data for successful empty responses
  • Improved error handling for failed JSON parsing

Summary by CodeRabbit

  • New Features

    • Graceful handling of empty or whitespace-only API responses (e.g., 204 or zero content), returning a successful result without data.
    • Apply authentication tokens only when present, avoiding spurious token updates.
  • Bug Fixes

    • Robust handling of non-JSON or malformed 2xx responses with clear parse-failure reporting and optional debug preview when enabled.
    • Improved extraction of error messages and HTTP status for clearer user-facing error info.
    • Consistent interpretation of varied response shapes, returning nested data or full body as appropriate.
  • Refactor

    • Streamlined response-reading and error-handling flow for greater resilience.

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Aug 17, 2025

⚠️ No Changeset found

Latest commit: bafc239

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Aug 17, 2025

Walkthrough

Reworks AccountApi.fetchJson and related token usage: reads raw response via response.text(), treats 204/empty bodies as success with undefined data, guards JSON.parse with additional error mapping for 2xx responses, interprets "error" and "data" shapes to construct Result or AccountError, and only sets tokens when result.data?.token exists. Public signatures unchanged.

Changes

Cohort / File(s) Summary of Changes
Account API: parsing, empty-response, and token handling
libs/portal-sdk/src/account.ts
Read raw response with response.text(); treat 204 or Content-Length: 0 (and whitespace-only bodies) as successful with data: undefined; guard JSON.parse and return AccountError("Failed to parse JSON response", status, ...) on 2xx parse failures (optionally including debug preview when VITE_ACCOUNT_API_DEBUG is "true"); when parsed JSON is an object, treat { error } as failure (construct message from string/error.message/unknown), { data } as success returning data, otherwise return entire parsed body as data; preserve outer unknown-error mapping and use result.data?.token before calling setToken. No public signatures changed.

Sequence Diagram(s)

sequenceDiagram
  participant C as Caller
  participant A as AccountApi.fetchJson
  participant S as HTTP Server

  C->>A: fetchJson(request)
  A->>S: HTTP request
  S-->>A: HTTP response (status, headers, body)

  alt 204 or Content-Length: 0 or body whitespace-only
    A-->>C: Result{ success: true, data: undefined }
  else Read raw body, attempt JSON.parse
    alt parse fails
      alt status 2xx
        A-->>C: Result{ success: false, error: AccountError("Failed to parse JSON response", status, details) }
      else
        A-->>C: Result{ success: false, error: mapped via handleFetchError }
      end
    else parse succeeds -> bodyParsed
      alt bodyParsed is object and has "error"
        A-->>C: Result{ success: false, error: AccountError(message, status, { error: bodyParsed.error }) }
      else bodyParsed has "data"
        A-->>C: Result{ success: true, data: bodyParsed.data }
      else
        A-->>C: Result{ success: true, data: bodyParsed }
      end
    end
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

I hop through headers, sniff the silent stream,
Empty body whispers—no panic, just a dream.
I catch the raw text, guard the parse with care,
Name the error if broken, or tuck data in my lair.
Little rabbit SDK, steady paws in the air 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between bc3a4b6 and bafc239.

📒 Files selected for processing (1)
  • libs/portal-sdk/src/account.ts (7 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/portal-sdk/src/account.ts
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch libs/portal-sdk

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
libs/portal-sdk/src/account.ts (1)

358-365: Make empty-body detection more robust (CORS, HEAD/205 cases).

content-length is often not exposed cross-origin and may be absent with chunked encoding. Also consider HEAD and HTTP 205 (Reset Content), both of which must not have a body.

Apply this diff to strengthen the check:

-      const contentLength = response.headers.get('content-length');
-      if (contentLength === '0' || response.status === 204) {
+      const contentLength = response.headers.get('content-length');
+      const isEmptyLen = contentLength !== null && Number(contentLength) === 0;
+      if (isEmptyLen || response.status === 204 || response.status === 205 || init.method?.toUpperCase() === "HEAD") {
         return {
           data: undefined as unknown as T, // Cast to T since void responses expect this
           success: true,
         };
       }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 786d5ef and d691d9d.

📒 Files selected for processing (1)
  • libs/portal-sdk/src/account.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
libs/portal-sdk/src/account.ts (1)
libs/portal-sdk/src/types.ts (1)
  • AccountError (23-44)

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.

Actionable comments posted: 1

🧹 Nitpick comments (1)
libs/portal-sdk/src/account.ts (1)

358-366: Empty-response handling is solid; consider also treating 205 as no-content.

Current early-return covers content-length: 0 and 204. 205 Reset Content is also a no-body status; you already handle it later via the text() + trim check, but adding it here avoids an unnecessary body read.

Apply this minimal tweak:

-      if (contentLength === '0' || response.status === 204) {
+      if (contentLength === "0" || response.status === 204 || response.status === 205) {
         return {
           data: undefined as unknown as T, // Cast to T since void responses expect this
           success: true,
         };
       }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d691d9d and bc3a4b6.

📒 Files selected for processing (1)
  • libs/portal-sdk/src/account.ts (4 hunks)
🔇 Additional comments (5)
libs/portal-sdk/src/account.ts (5)

115-117: Token assignment guarded — resolves prior crash risk.

Using optional chaining when reading token avoids accessing undefined on empty-success responses. LGTM.


147-149: Token refresh guard on ping looks good.

Prevents setting an undefined token on empty/partial responses. LGTM.


275-277: Token set guarded in validateOtp — consistent and correct.

Matches the login/ping hardening and removes a potential undefined dereference. LGTM.


367-374: Whitespace-only body detection is a good fallback.

Reading text once and treating empty/whitespace-only bodies as success (void) is robust against proxies omitting content-length. Nicely done.


394-399: Error shape handling is robust and preserves server details.

Gracefully supports both string and object error payloads and passes through the original error object. LGTM.

…ntApi

- Added null checks for token access using optional chaining
- Implemented robust empty response handling
- Added proper JSON parsing with error handling
- Improved error message extraction from response bodies
- Added raw response data to error objects for debugging
@pcfreak30 pcfreak30 merged commit b019b62 into develop Aug 17, 2025
1 of 2 checks passed
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