Skip to content

fix(gotrue): preserve the error message on 5xx responses - #1653

Open
spydon wants to merge 3 commits into
mainfrom
lukasklingsbo/sdk-1418-parity-auth-preserve-http-status-text
Open

fix(gotrue): preserve the error message on 5xx responses#1653
spydon wants to merge 3 commits into
mainfrom
lukasklingsbo/sdk-1418-parity-auth-preserve-http-status-text

Conversation

@spydon

@spydon spydon commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

What

GotrueFetch._handleError short-circuited on statusCode >= 500 before it looked at the body, and set message: response.body unconditionally. That meant:

  • a JSON error body such as {"code":"unexpected_failure","msg":"Error sending confirmation email"} surfaced as the raw JSON string instead of the server sent message
  • an HTML error page from a proxy surfaced as a wall of markup
  • an empty body surfaced as an empty message

The 5xx check now runs after the body is parsed, so the server sent message wins. When the body isn't JSON (or is empty), the message falls back to the response's reason phrase, and then to a synthesized HTTP <status> since HTTP/2 responses carry no reason phrase.

Non-5xx handling is untouched: a non-JSON 4xx body still throws AuthUnknownException.

Response Before After
500 with {"msg":"Error sending confirmation email"} {"msg":"Error sending confirmation email"} Error sending confirmation email
502 with an HTML body, reason phrase Bad Gateway the full HTML Bad Gateway
502 with an HTML body, no reason phrase the full HTML HTTP 502
503 with an empty body `` Service Unavailable

AuthRetryableFetchException and its statusCode are unchanged, so retry behavior is unaffected.

Why

Parity with supabase-js, which made the same reordering in supabase/supabase-js#2587 (a6bcd6ae).

Fixes #1651

Summary by CodeRabbit

  • Bug Fixes
    • Improved authentication error handling for server-side failures.
    • Retryable server errors now consistently provide a meaningful message and status code.
    • Error messages now use available server details, HTTP reason phrases, or a clear status-based fallback.
    • Improved handling of empty and malformed error responses.
    • Non-JSON client errors are now reported with the appropriate unknown-error classification.

`_handleError` short-circuited on `statusCode >= 500` before parsing the
body, so a JSON error body surfaced as a raw JSON string and an HTML or
empty body surfaced as noise. Parse the body first, and when it isn't
JSON fall back to the response's reason phrase, then to a synthesized
`HTTP <status>` for HTTP/2 responses which carry no reason phrase.
@spydon
spydon requested a review from a team as a code owner August 5, 2026 15:05
@github-actions github-actions Bot added the auth This issue or pull request is related to authentication label Aug 5, 2026
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

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

Next review available in: 13 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 4dc23383-5c7c-487c-8b38-44c769816c2a

📥 Commits

Reviewing files that changed from the base of the PR and between 7682c69 and 0f37320.

📒 Files selected for processing (3)
  • packages/gotrue/lib/src/fetch.dart
  • packages/gotrue/test/custom_http_client.dart
  • packages/gotrue/test/fetch_test.dart
📝 Walkthrough

Walkthrough

Gotrue fetch handling now provides fallback messages for retryable HTTP errors. Tests cover JSON and non-JSON 5xx responses, reason phrases, synthesized status messages, and non-retryable 4xx decode failures.

Changes

Gotrue server error handling

Layer / File(s) Summary
Retryable error message selection
packages/gotrue/lib/src/fetch.dart
The fetch layer uses the HTTP reason phrase or HTTP <status> fallback for retryable responses. It throws AuthRetryableFetchException for empty bodies, JSON decode failures, and decoded 5xx errors.
Server error test coverage
packages/gotrue/test/custom_http_client.dart, packages/gotrue/test/fetch_test.dart
Tests use configurable raw HTTP responses to verify JSON and non-JSON 5xx messages, reason phrase fallbacks, and unknown exceptions for non-JSON 4xx responses.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related issues

Possibly related PRs

Suggested reviewers: dshukertjr

Sequence Diagram(s)

sequenceDiagram
  participant GotrueFetch
  participant HTTPClient
  participant AuthRetryableFetchException
  GotrueFetch->>HTTPClient: request HTTP response
  HTTPClient-->>GotrueFetch: status, reason phrase, and body
  GotrueFetch->>AuthRetryableFetchException: throw status or decoded message for 500+ responses
Loading
🚥 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 describes the primary change: preserving error messages on 5xx HTTP responses, which is the main objective of the pull request.
Linked Issues check ✅ Passed The pull request implements all acceptance criteria from issue #1651: JSON error message parsing, HTTP reason phrase fallback, HTTP fallback for empty reason phrases, and unit test coverage for standard and edge cases.
Out of Scope Changes check ✅ Passed All changes in fetch.dart, custom_http_client.dart, and fetch_test.dart are directly related to implementing the error message preservation feature and its test coverage.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch lukasklingsbo/sdk-1418-parity-auth-preserve-http-status-text

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
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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 `@packages/gotrue/lib/src/fetch.dart`:
- Line 65: Wrap the comment near the fetch response decoding logic so each Dart
source line stays within the repository’s 80-character limit, preserving its
wording and meaning; run dart format afterward.

In `@packages/gotrue/test/fetch_test.dart`:
- Around line 131-145: Add a separate 5xx test in the fetch test group using
RawBodyHttpClient with reasonPhrase explicitly set to an empty string, and
assert through _expectRetryableFetch that the message is HTTP 502 and statusCode
is 502. Keep the existing unset-reason test to retain null coverage, and run the
relevant gotrue test suite.
🪄 Autofix

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 60293d1a-c509-4699-95e3-0f4df2abc5e2

📥 Commits

Reviewing files that changed from the base of the PR and between 3e23ddc and 7682c69.

📒 Files selected for processing (3)
  • packages/gotrue/lib/src/fetch.dart
  • packages/gotrue/test/custom_http_client.dart
  • packages/gotrue/test/fetch_test.dart

Comment thread packages/gotrue/lib/src/fetch.dart Outdated
Comment thread packages/gotrue/test/fetch_test.dart
Also wrap the empty body comment to fit within 80 characters.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR adjusts GotrueFetch._handleError so 5xx responses preserve a meaningful error message by parsing JSON bodies first, and falling back to the HTTP reason phrase (or HTTP <status> when absent), aligning behavior with supabase-js and fixing #1651.

Changes:

  • Reorders 5xx error handling to parse JSON bodies before throwing AuthRetryableFetchException.
  • Adds a reason-phrase / HTTP <status> fallback for empty or non-JSON 5xx responses.
  • Adds unit tests covering JSON vs non-JSON 5xx behavior and validates non-JSON 4xx remains AuthUnknownException.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
packages/gotrue/lib/src/fetch.dart Reorders 5xx error handling and adds fallback message derivation via reason phrase / synthesized status text.
packages/gotrue/test/fetch_test.dart Adds regression tests for server-error messaging behavior across JSON/non-JSON/empty bodies.
packages/gotrue/test/custom_http_client.dart Adds a raw-body test client to simulate non-JSON/HTML error responses.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +250 to +255
return StreamedResponse(
Stream.value(utf8.encode(body)),
statusCode,
request: request,
reasonPhrase: reasonPhrase,
);
Comment on lines +147 to +159
test('falls back to the reason phrase on an empty 5xx body', () async {
final client = RawBodyHttpClient(
'',
statusCode: 503,
reasonPhrase: 'Service Unavailable',
);

await _expectRetryableFetch(
client,
message: 'Service Unavailable',
statusCode: '503',
);
});
Also declare a UTF-8 charset on `RawBodyHttpClient` responses, since
`package:http` otherwise decodes the body as Latin-1.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auth This issue or pull request is related to authentication

Projects

None yet

Development

Successfully merging this pull request may close these issues.

parity(auth): preserve HTTP status text on non-JSON 5xx error responses [from supabase-js]

3 participants