Skip to content

feat(errors): expose response headers on APIError - #188

Merged
lumpinif merged 8 commits into
mainfrom
feat/error-response-headers
Dec 1, 2026
Merged

lumpinif merged 8 commits into
mainfrom
feat/error-response-headers

Conversation

@lumpinif

@lumpinif lumpinif commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

What

When the API refuses a call, the caller can now read the response headers from the error, including x-fish-trace-id and x-fish-error-code, and pass them to support. Part of FISH-2233.

APIError gains headers. It is set on the APIError raised for an HTTP call and for a refused realtime speech-to-text handshake, sync and async. The SDK names no header and promises none: the error carries whatever the response had.

Public interface

  • APIError.__init__(status, message, body=None, headers=None): a new optional fourth argument, a mapping of header names to values. Inherited by AuthenticationError, PermissionError, NotFoundError, RateLimitError and ServerError.
  • New attribute headers on those six classes: an httpx.Headers, a copy of what was given, empty when nothing was.
  • No new class, export, option or parameter on a client method.

Behaviour changes

Before After
getattr(err, "headers", None) on an APIError None an httpx.Headers, possibly empty
json.dumps(vars(err)) on an APIError works raises TypeError: Headers is not JSON serializable

Existing two- and three-argument constructor calls, the exception classes raised, and status, message, body and str(err) are unchanged.

Not changed

tts.stream_websocket: a handshake that the server refuses still raises httpx_ws.WebSocketUpgradeError, whose response.headers already has the headers. Wrapping it would break existing except WebSocketUpgradeError code. The README shows this path in one line.

Calls that fail after they started (an error after the WebSocket opened, a stream that breaks midway) have no error response, so they need a different design.

main now has #196, which raises an APIError for every error response body. This branch is merged with it: #196's body reading is kept as it is, and its _api_error(...) call also passes response.headers, so an error whose body is not a JSON object carries the headers too.

Verification

poe check and the test suite pass. Tests in tests/unit/test_error_headers.py run the client against a local HTTP server and the scripted WebSocket server: an HTTP error carries the headers (sync and async, streaming and non-streaming calls), every error class carries them, a header the response does not have is absent, a header value outside ASCII arrives as sent, an error built by hand has empty headers or takes a value outside ASCII, a refused tts.stream_websocket handshake exposes them on the upgrade error, and an error whose body is null, [] or not JSON carries them. The two existing refused-upgrade tests of realtime speech to text assert the headers too. Against production with an invalid key: /v1/tts 401 and refused speech-to-text and text-to-speech handshakes expose the trace id and invalid_api_key; a /wallet 401 has neither header.

Summary by CodeRabbit

  • New Features
    • API errors now expose response headers, including trace IDs and error codes when provided.
    • WebSocket handshake errors now include the rejected response’s headers for easier troubleshooting.
  • Documentation
    • Added guidance on accessing response headers from API and WebSocket errors.

APIError gains headers, set from every HTTP error response and from a
refused realtime speech-to-text handshake, so a caller can read
x-fish-trace-id and x-fish-error-code.
@lumpinif
lumpinif requested review from abersheeran and a lite review from Copilot November 26, 2026 12:19
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-26T12:19:24.560795Z
We couldn’t complete this review. Comment @codex review to try again.
a42cbcf PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

APIError now stores response headers. HTTP error handling and refused WebSocket upgrades pass response headers into error construction. Tests and README guidance cover header access, including cases where headers are absent.

Changes: Error response headers

Layer / File(s) Summary
HTTP error header propagation
src/fishaudio/exceptions.py, src/fishaudio/core/client_wrapper.py, tests/unit/test_error_headers.py, README.md
APIError accepts optional headers and stores them as httpx.Headers. HTTP status handling passes response headers to the selected exception. Tests cover present and absent headers in synchronous and asynchronous clients. The README documents header access.
WebSocket refusal headers
src/fishaudio/resources/asr_realtime.py, tests/unit/realtime_server.py, tests/unit/test_asr_realtime.py, tests/unit/test_error_headers.py
Refused WebSocket upgrades pass response headers into error construction. Tests verify trace and error-code headers for synchronous and asynchronous refusals.

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

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant HTTPResponse
  participant RaiseForStatus as _raise_for_status
  participant ApiErrorFactory as _api_error
  participant APIError
  HTTPResponse->>RaiseForStatus: status, body, and headers
  RaiseForStatus->>ApiErrorFactory: status, message, body, and headers
  ApiErrorFactory->>APIError: construct error with headers
  APIError-->>ApiErrorFactory: error stores headers
Loading

Possibly related PRs

Merge Risk: Minimal · up to ff311

This change exposes response headers on API errors without altering existing exception types or the status, message and body behavior. No actionable merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "feat(errors): expose response headers on APIError" matches the main change. The changeset adds an optional headers argument to APIError.init, stores the headers on APIError and its subc…
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.
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Title check

Explanation

The title "feat(errors): expose response headers on APIError" matches the main change. The changeset adds an optional headers argument to APIError.init, stores the headers on APIError and its subclasses, and passes response headers from the HTTP and realtime WebSocket error paths. The title is specific and uses the conventional commit format.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6c439380-1a09-46c8-8eb7-79fef25dad4b
Commits

Reviewing files that changed from the base of the PR and between ae2fa1a and ff3115c.

Files selected for processing: 7

  • README.md
  • src/fishaudio/core/client_wrapper.py
  • src/fishaudio/exceptions.py
  • src/fishaudio/resources/asr_realtime.py
  • tests/unit/realtime_server.py
  • tests/unit/test_asr_realtime.py
  • tests/unit/test_error_headers.py

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 0 remain after this review.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
src/fishaudio/core/client_wrapper.py 95.15% <100.00%> (+0.63%) ⬆️
src/fishaudio/exceptions.py 100.00% <100.00%> (ø)
src/fishaudio/resources/asr_realtime.py 97.25% <100.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

🟡 Changes recommended

The README support-header example is invalid because the separate code block begins with an orphaned except and omits the APIError import, causing syntax and name errors for users who copy it.

1 open issue
What changed in this PR

This PR exposes HTTP response headers through APIError, allowing callers to retrieve diagnostic values such as trace IDs and error codes from failed HTTP requests and refused ASR realtime handshakes.

Changes:

  • Added an httpx.Headers attribute to APIError, including empty headers when no response exists.
  • Propagated response headers through synchronous and asynchronous HTTP errors and refused ASR handshakes.
  • Added tests, test-server headers, and README guidance while preserving the existing TTS WebSocket upgrade exception behavior.
File Description
tests/​unit/​test_error_headers.py Adds coverage for response-header propagation across HTTP errors, missing headers, and TTS upgrade errors.
tests/​unit/​test_asr_realtime.py Verifies headers on synchronous and asynchronous refused ASR realtime handshakes.
tests/​unit/​realtime_server.py Adds diagnostic headers to refused handshake responses in the test server.
src/​fishaudio/​resources/​asr_realtime.py Preserves response headers when converting refused realtime handshake failures into API errors.
src/​fishaudio/​exceptions.py Adds the optional headers attribute and constructor support to APIError.
src/​fishaudio/​core/​client_wrapper.py Passes HTTP response headers into mapped API exceptions.
README.md Documents accessing diagnostic headers from API and WebSocket errors.

Review effort: Lite

Comment thread README.md Resolved
…ror; cover the non-streaming error paths

Also corrects the message docstring, a fixture comment and one README
sentence so that each says only what the code does.
Keeps main's error-body reading (#196) and passes the response headers
to its APIError. A test checks that an error whose body is not a JSON
object carries the headers.
@lumpinif
lumpinif merged commit 47a9c09 into main Dec 1, 2026
27 checks passed
@lumpinif
lumpinif deleted the feat/error-response-headers branch December 1, 2026 09:11
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.

2 participants