From a42cbcf1d9485e946530387ac1c77a3c522f3ee3 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:51:26 -0800 Subject: [PATCH 1/4] feat(errors): expose response headers on APIError 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. --- README.md | 9 ++ src/fishaudio/core/client_wrapper.py | 30 ++++--- src/fishaudio/exceptions.py | 21 ++++- src/fishaudio/resources/asr_realtime.py | 6 +- tests/unit/realtime_server.py | 13 ++- tests/unit/test_asr_realtime.py | 4 + tests/unit/test_error_headers.py | 107 ++++++++++++++++++++++++ 7 files changed, 174 insertions(+), 16 deletions(-) create mode 100644 tests/unit/test_error_headers.py diff --git a/README.md b/README.md index f1ca832..2281372 100644 --- a/README.md +++ b/README.md @@ -325,6 +325,15 @@ except FishAudioError as e: print(f"API error: {e}") ``` +Every `APIError` carries the headers of the error response. When you contact support, include the trace id and the error code. Either can be absent. + +```python +except APIError as e: + print(e.headers.get("x-fish-trace-id"), e.headers.get("x-fish-error-code")) +``` + +A refused `tts.stream_websocket` connection raises `httpx_ws.WebSocketUpgradeError`; read the same headers from `e.response.headers`. + ## Resources - **Documentation:** [SDK Guide](https://docs.fish.audio/developer-guide/sdk-guide/python/) | [API Reference](https://docs.fish.audio/api-reference/sdk/python/) diff --git a/src/fishaudio/core/client_wrapper.py b/src/fishaudio/core/client_wrapper.py index be74c73..dc401bb 100644 --- a/src/fishaudio/core/client_wrapper.py +++ b/src/fishaudio/core/client_wrapper.py @@ -19,19 +19,25 @@ from .request_options import RequestOptions -def _api_error(status: int, message: str, body: Optional[str] = None) -> APIError: +def _api_error( + status: int, + message: str, + body: Optional[str] = None, + headers: Optional[httpx.Headers] = None, +) -> APIError: """Build the exception that matches an HTTP error status.""" + error_class = APIError if status == 401: - return AuthenticationError(status, message, body) - if status == 403: - return PermissionError(status, message, body) - if status == 404: - return NotFoundError(status, message, body) - if status == 429: - return RateLimitError(status, message, body) - if status >= 500: - return ServerError(status, message, body) - return APIError(status, message, body) + error_class = AuthenticationError + elif status == 403: + error_class = PermissionError + elif status == 404: + error_class = NotFoundError + elif status == 429: + error_class = RateLimitError + elif status >= 500: + error_class = ServerError + return error_class(status, message, body, headers) def _raise_for_status(response: httpx.Response) -> None: @@ -45,7 +51,7 @@ def _raise_for_status(response: httpx.Response) -> None: except JSONDecodeError: message = response.text or httpx.codes.get_reason_phrase(status) - raise _api_error(status, message, response.text) + raise _api_error(status, message, response.text, response.headers) class BaseClientWrapper: diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index e8ac4ac..c9f6790 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -1,7 +1,10 @@ """Custom exceptions for the Fish Audio SDK.""" +from collections.abc import Mapping from typing import Optional +import httpx + class FishAudioError(Exception): """Base exception for all Fish Audio SDK errors.""" @@ -10,12 +13,26 @@ class FishAudioError(Exception): class APIError(FishAudioError): - """Raised when the API returns an error response.""" + """Raised when the API returns an error response. + + Attributes: + status: HTTP status code + message: Error message from the response + body: Response body, if it was read + headers: Headers of the error response (empty if there are none) + """ - def __init__(self, status: int, message: str, body: Optional[str] = None): + def __init__( + self, + status: int, + message: str, + body: Optional[str] = None, + headers: Optional[Mapping[str, str]] = None, + ): self.status = status self.message = message self.body = body + self.headers = httpx.Headers(headers) super().__init__(f"HTTP {status}: {message}") diff --git a/src/fishaudio/resources/asr_realtime.py b/src/fishaudio/resources/asr_realtime.py index a36413c..aa62fe2 100644 --- a/src/fishaudio/resources/asr_realtime.py +++ b/src/fishaudio/resources/asr_realtime.py @@ -133,7 +133,11 @@ def _upgrade_error(response: httpx.Response) -> Exception: """The WebSocket upgrade was refused (401, 402, 429, ...): map the HTTP status.""" status = response.status_code # httpx-ws closes the response before the body can be read. - return _api_error(status, httpx.codes.get_reason_phrase(status) or "Upgrade failed") + return _api_error( + status, + httpx.codes.get_reason_phrase(status) or "Upgrade failed", + headers=response.headers, + ) class _Protocol: diff --git a/tests/unit/realtime_server.py b/tests/unit/realtime_server.py index 550e573..11784c3 100644 --- a/tests/unit/realtime_server.py +++ b/tests/unit/realtime_server.py @@ -34,6 +34,13 @@ } +# Sent with every refused handshake, as the API does. +REJECT_HEADERS = [ + (b"x-fish-trace-id", b"trace-123"), + (b"x-fish-error-code", b"invalid_api_key"), +] + + class ClientGone(Exception): """The client closed the connection.""" @@ -70,7 +77,11 @@ def _read(self) -> None: self.path = event.target self.headers = {k.decode(): v.decode() for k, v in event.extra_headers} if self._reject_status is not None: - self._write(RejectConnection(status_code=self._reject_status)) + self._write( + RejectConnection( + status_code=self._reject_status, headers=REJECT_HEADERS + ) + ) raise ClientGone self._write(AcceptConnection()) elif isinstance(event, BytesMessage): diff --git a/tests/unit/test_asr_realtime.py b/tests/unit/test_asr_realtime.py index 20941bb..5347e40 100644 --- a/tests/unit/test_asr_realtime.py +++ b/tests/unit/test_asr_realtime.py @@ -696,6 +696,8 @@ def test_refused_upgrade_raises_api_error(self, status, error_class): ): list(client.asr.stream_websocket(iter([CHUNK]))) assert exc_info.value.status == status + assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" + assert exc_info.value.headers["x-fish-error-code"] == "invalid_api_key" def test_leaving_the_loop_early_closes_the_connection(self): with serving(open_ended_script) as (server, client): @@ -1076,6 +1078,8 @@ async def test_refused_upgrade_raises_api_error(self, status, error_class): async for _ in client.asr.stream_websocket(aiter_chunks(CHUNK)): pass assert exc_info.value.status == status + assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" + assert exc_info.value.headers["x-fish-error-code"] == "invalid_api_key" async def test_leaving_the_loop_early_closes_the_connection(self): async with aserving(open_ended_script) as (server, client): diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py new file mode 100644 index 0000000..fb4a1f7 --- /dev/null +++ b/tests/unit/test_error_headers.py @@ -0,0 +1,107 @@ +"""An APIError carries the headers of the error response. + +The tests run the real client against a local HTTP server, and a refused +WebSocket handshake against the scripted server in realtime_server.py. +""" + +import contextlib +import threading +from http.server import BaseHTTPRequestHandler, HTTPServer + +import pytest +from httpx_ws import WebSocketUpgradeError + +from fishaudio import APIError, AsyncFishAudio, AuthenticationError, FishAudio + +from .realtime_server import RealtimeServer + + +class _Refuse(BaseHTTPRequestHandler): + """401 with the API's diagnostic headers on /v1, a bare 404 elsewhere.""" + + def _respond(self): + self.rfile.read(int(self.headers.get("content-length", 0))) + if self.path.startswith("/v1/"): + body = b'{"status":401,"message":"Invalid Token"}' + self.send_response(401) + self.send_header("x-fish-trace-id", "trace-123") + self.send_header("x-fish-error-code", "invalid_api_key") + else: + body = b'{"status":404,"message":"Not found"}' + self.send_response(404) + self.send_header("content-type", "application/json") + self.send_header("content-length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + do_GET = do_POST = _respond + + def log_message(self, *args): + pass + + +@contextlib.contextmanager +def refusing_server(): + server = HTTPServer(("127.0.0.1", 0), _Refuse) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_port}" + finally: + server.shutdown() + server.server_close() + thread.join() + + +def test_http_error_carries_the_response_headers(): + with ( + refusing_server() as url, + FishAudio(api_key="k", base_url=url) as client, + pytest.raises(AuthenticationError) as exc_info, + ): + client.tts.convert(text="hi") + error = exc_info.value + assert error.status == 401 + assert error.message == "Invalid Token" + assert error.headers["x-fish-trace-id"] == "trace-123" + assert error.headers["X-Fish-Error-Code"] == "invalid_api_key" # any casing + + +async def test_http_error_carries_the_response_headers_async(): + with refusing_server() as url: + async with AsyncFishAudio(api_key="k", base_url=url) as client: + with pytest.raises(AuthenticationError) as exc_info: + await client.tts.convert(text="hi") + assert exc_info.value.headers["x-fish-trace-id"] == "trace-123" + + +def test_headers_the_response_does_not_have_are_absent(): + with ( + refusing_server() as url, + FishAudio(api_key="k", base_url=url) as client, + pytest.raises(APIError) as exc_info, + ): + client.account.get_credits() + assert exc_info.value.status == 404 + assert exc_info.value.headers.get("x-fish-trace-id") is None + + +def test_error_built_without_headers_has_empty_headers(): + error = APIError(400, "Bad Request") + assert error.headers.get("x-fish-trace-id") is None + assert len(error.headers) == 0 + + +def test_refused_tts_websocket_exposes_the_headers_on_the_upgrade_error(): + """The README's second path: tts.stream_websocket is not wrapped.""" + server = RealtimeServer(lambda conn: None, reject_status=401) + try: + with ( + FishAudio(api_key="k", base_url=server.url) as client, + pytest.raises(WebSocketUpgradeError) as exc_info, + ): + list(client.tts.stream_websocket(iter(["hi"]))) + finally: + server.close() + assert exc_info.value.response.status_code == 401 + assert exc_info.value.response.headers["x-fish-trace-id"] == "trace-123" From d04492e613a71715b66478f19c068dd09c101263 Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:22:27 -0800 Subject: [PATCH 2/4] test: every error class carries the response headers --- tests/unit/test_error_headers.py | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py index fb4a1f7..fa70ede 100644 --- a/tests/unit/test_error_headers.py +++ b/tests/unit/test_error_headers.py @@ -8,10 +8,18 @@ import threading from http.server import BaseHTTPRequestHandler, HTTPServer +import httpx import pytest from httpx_ws import WebSocketUpgradeError from fishaudio import APIError, AsyncFishAudio, AuthenticationError, FishAudio +from fishaudio.core.client_wrapper import _raise_for_status +from fishaudio.exceptions import ( + NotFoundError, + PermissionError, + RateLimitError, + ServerError, +) from .realtime_server import RealtimeServer @@ -105,3 +113,29 @@ def test_refused_tts_websocket_exposes_the_headers_on_the_upgrade_error(): server.close() assert exc_info.value.response.status_code == 401 assert exc_info.value.response.headers["x-fish-trace-id"] == "trace-123" + + +@pytest.mark.parametrize( + ("status", "error_class"), + [ + (400, APIError), + (401, AuthenticationError), + (403, PermissionError), + (404, NotFoundError), + (429, RateLimitError), + (503, ServerError), + ], +) +def test_every_error_class_carries_the_headers(status, error_class): + response = httpx.Response( + status, + headers={"x-fish-trace-id": "trace-123"}, + json={"message": "refused"}, + request=httpx.Request("GET", "https://api.fish.audio/v1/tts"), + ) + + with pytest.raises(APIError) as caught: + _raise_for_status(response) + + assert type(caught.value) is error_class + assert caught.value.headers["x-fish-trace-id"] == "trace-123" From ae2fa1aa1893d7d699451fbb9f939baa842fa6ec Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Thu, 26 Nov 2026 06:15:20 -0800 Subject: [PATCH 3/4] docs: make the error-headers README example a complete block --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 2281372..e6d5585 100644 --- a/README.md +++ b/README.md @@ -328,6 +328,10 @@ except FishAudioError as e: Every `APIError` carries the headers of the error response. When you contact support, include the trace id and the error code. Either can be absent. ```python +from fishaudio.exceptions import APIError + +try: + audio = client.tts.convert(text="Hello!") except APIError as e: print(e.headers.get("x-fish-trace-id"), e.headers.get("x-fish-error-code")) ``` From 4be5e3484f550b991cb8289ddf278d5857b5dd7d Mon Sep 17 00:00:00 2001 From: Felix Lu <58391009+lumpinif@users.noreply.github.com> Date: Mon, 30 Nov 2026 06:30:34 -0800 Subject: [PATCH 4/4] fix(errors): accept header values outside ASCII on a hand-built APIError; 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. --- README.md | 2 +- src/fishaudio/exceptions.py | 9 +++++++-- tests/unit/realtime_server.py | 2 +- tests/unit/test_error_headers.py | 27 +++++++++++++++++++++++++++ 4 files changed, 36 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 4790eec..4277014 100644 --- a/README.md +++ b/README.md @@ -346,7 +346,7 @@ except APIError as e: print(e.headers.get("x-fish-trace-id"), e.headers.get("x-fish-error-code")) ``` -A refused `tts.stream_websocket` connection raises `httpx_ws.WebSocketUpgradeError`; read the same headers from `e.response.headers`. +A `tts.stream_websocket` handshake that the server refuses raises `httpx_ws.WebSocketUpgradeError`; read the same headers from `e.response.headers`. ## Resources diff --git a/src/fishaudio/exceptions.py b/src/fishaudio/exceptions.py index c9f6790..ae8521b 100644 --- a/src/fishaudio/exceptions.py +++ b/src/fishaudio/exceptions.py @@ -17,7 +17,8 @@ class APIError(FishAudioError): Attributes: status: HTTP status code - message: Error message from the response + message: Error message from the response, or the HTTP reason phrase + for a refused WebSocket handshake body: Response body, if it was read headers: Headers of the error response (empty if there are none) """ @@ -32,7 +33,11 @@ def __init__( self.status = status self.message = message self.body = body - self.headers = httpx.Headers(headers) + if isinstance(headers, httpx.Headers): + self.headers = headers.copy() + else: + # httpx encodes str values as ASCII unless told otherwise. + self.headers = httpx.Headers(headers, encoding="utf-8") super().__init__(f"HTTP {status}: {message}") diff --git a/tests/unit/realtime_server.py b/tests/unit/realtime_server.py index 11784c3..3fb1cf1 100644 --- a/tests/unit/realtime_server.py +++ b/tests/unit/realtime_server.py @@ -34,7 +34,7 @@ } -# Sent with every refused handshake, as the API does. +# Test values, sent with every handshake this server refuses. REJECT_HEADERS = [ (b"x-fish-trace-id", b"trace-123"), (b"x-fish-error-code", b"invalid_api_key"), diff --git a/tests/unit/test_error_headers.py b/tests/unit/test_error_headers.py index fa70ede..c4009e3 100644 --- a/tests/unit/test_error_headers.py +++ b/tests/unit/test_error_headers.py @@ -37,6 +37,7 @@ def _respond(self): else: body = b'{"status":404,"message":"Not found"}' self.send_response(404) + self.send_header("x-detail", "café") self.send_header("content-type", "application/json") self.send_header("content-length", str(len(body))) self.end_headers() @@ -91,9 +92,35 @@ def test_headers_the_response_does_not_have_are_absent(): ): client.account.get_credits() assert exc_info.value.status == 404 + assert exc_info.value.headers["content-type"] == "application/json" assert exc_info.value.headers.get("x-fish-trace-id") is None +async def test_headers_the_response_does_not_have_are_absent_async(): + with refusing_server() as url: + async with AsyncFishAudio(api_key="k", base_url=url) as client: + with pytest.raises(APIError) as exc_info: + await client.account.get_credits() + assert exc_info.value.status == 404 + assert exc_info.value.headers["content-type"] == "application/json" + assert exc_info.value.headers.get("x-fish-trace-id") is None + + +def test_a_header_value_outside_ascii_arrives_as_sent(): + with ( + refusing_server() as url, + FishAudio(api_key="k", base_url=url) as client, + pytest.raises(APIError) as exc_info, + ): + client.account.get_credits() + assert exc_info.value.headers["x-detail"] == "café" + + +def test_error_built_by_hand_takes_a_header_value_outside_ascii(): + error = APIError(400, "Bad Request", headers={"x-detail": "café"}) + assert error.headers["x-detail"] == "café" + + def test_error_built_without_headers_has_empty_headers(): error = APIError(400, "Bad Request") assert error.headers.get("x-fish-trace-id") is None