Skip to content

Do not swallow non-JSON http error responses#1250

Merged
sanders41 merged 2 commits into
mainfrom
python-1209-create_index-and-get_index-giving-json-error
Jun 23, 2026
Merged

Do not swallow non-JSON http error responses#1250
sanders41 merged 2 commits into
mainfrom
python-1209-create_index-and-get_index-giving-json-error

Conversation

@Strift

@Strift Strift commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Pull Request

Related issue

Fixes #129

What does this PR do?

  • Use raw response text when an API error body is not valid JSON

AI disclosure

Cursor with gpt-5.4-low and codex-5.3-low

PR checklist

Please check if your PR fulfills the following requirements:

  • Did you use any AI tool while implementing this PR (code, tests, docs, etc.)? If yes, disclose it in the PR description and describe what it was used for. AI usage is allowed when it is disclosed.
  • Does this PR fix an existing issue, or have you listed the changes applied in the PR description (and why they are needed)?
  • Have you read the contributing guidelines?
  • Have you made sure that the title is accurate and descriptive of the changes?

Thank you so much for contributing to Meilisearch!

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved error handling for API failures when the response body is malformed or not a JSON object. The error message now reliably falls back to the raw response text instead of leaving it unset or causing parsing-related issues.
  • Tests

    • Added regression tests covering non-JSON (e.g., HTML) and JSON-but-not-object (e.g., array) error responses.

@Strift Strift added the bug Something isn't working label Jun 23, 2026
@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

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

Run ID: da84df69-2c2a-45ef-8adf-62fb13802157

📥 Commits

Reviewing files that changed from the base of the PR and between 5e2f14e and ef693f6.

📒 Files selected for processing (2)
  • meilisearch/errors.py
  • tests/errors/test_api_error_meilisearch.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • meilisearch/errors.py

📝 Walkthrough

Walkthrough

MeilisearchApiError.__init__ now wraps json.loads(request.text) in a try/except json.JSONDecodeError and validates the parsed JSON is a dict before extracting message, code, link, and type. If parsing fails or the result is not a dict, it falls back to raw request.text. Two regression tests cover non-JSON (HTML) and non-object (JSON array) response bodies.

Changes

Non-JSON error response fallback

Layer / File(s) Summary
JSON parse fallback with dict type validation
meilisearch/errors.py
MeilisearchApiError.__init__ wraps json.loads in try/except json.JSONDecodeError, validates the parsed JSON is a dict before extracting fields, and sets self.message to raw request.text on parse failure or non-dict payload. When a dict message field is absent or falsy, also falls back to request.text.
Regression tests for non-JSON and non-dict JSON responses
tests/errors/test_api_error_meilisearch.py
Two new tests mock HTTP 502 responses: one with an HTML body (non-JSON), another with a valid JSON array body (non-dict). Both assert MeilisearchApiError preserves status_code=502, sets message to the raw response text, and leaves code, link, and type as None.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐇 A gateway threw HTML my way,
JSON was nowhere to be found that day.
I caught the error, checked the type,
And kept the text when parsing's not right.
Now arrays, HTML, and missing fields all play! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'Do not swallow non-JSON http error responses' directly and clearly describes the main objective of the changeset: improving error handling to gracefully handle non-JSON HTTP error responses instead of crashing.
Linked Issues check ✅ Passed The PR fully addresses issue #129 by implementing a try/except mechanism to parse JSON error responses and falling back to raw response text when parsing fails, resolving the JSONDecodeError crash.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the error handling issue. The modifications to MeilisearchApiError and corresponding regression tests are tightly focused on handling non-JSON HTTP error responses.

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

✨ 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 python-1209-create_index-and-get_index-giving-json-error

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: 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 `@meilisearch/errors.py`:
- Around line 40-43: The json.loads(request.text) call may return valid JSON
that is not a dictionary (such as a list or string), and calling .get() methods
on non-dict types will raise an AttributeError. Add a type check to verify that
json_data is actually a dictionary before attempting to call .get() on it. If
json_data is not a dictionary, fall back to using request.text as the message
value. Apply this guard to all the .get() calls on json_data for the message,
code, link, and type attributes.
🪄 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

Run ID: 41cd5f41-99d1-4306-a125-2728b3a2f325

📥 Commits

Reviewing files that changed from the base of the PR and between 1464823 and 5e2f14e.

📒 Files selected for processing (2)
  • meilisearch/errors.py
  • tests/errors/test_api_error_meilisearch.py

Comment thread meilisearch/errors.py Outdated
@Strift Strift requested a review from sanders41 June 23, 2026 06:34
@sanders41 sanders41 added this pull request to the merge queue Jun 23, 2026
Merged via the queue into main with commit 4b65a38 Jun 23, 2026
10 checks passed
@sanders41 sanders41 deleted the python-1209-create_index-and-get_index-giving-json-error branch June 23, 2026 13:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MeiliSearchApiError crashes with JSONDecodeError when server returns non-JSON response

2 participants