gateway: handle non-JSON upstream responses with 502 and upstream text

This commit is contained in:
2026-03-21 09:43:37 +01:00
parent 7208c45768
commit e6da9924ff

View File

@@ -61,16 +61,23 @@ async def _get_health(client: httpx.AsyncClient, base: str) -> Dict[str, Any]:
async def _post_json(client: httpx.AsyncClient, url: str, payload: Dict[str, Any]) -> Dict[str, Any]: async def _post_json(client: httpx.AsyncClient, url: str, payload: Dict[str, Any]) -> Dict[str, Any]:
r = await client.post(url, json=payload) r = await client.post(url, json=payload)
if r.status_code >= 400: if r.status_code >= 400:
raise HTTPException(status_code=502, detail=f"Upstream error {url}: {r.status_code} {r.text[:200]}") raise HTTPException(status_code=502, detail=f"Upstream error {url}: {r.status_code} {r.text[:1000]}")
return r.json() try:
return r.json()
except Exception:
# upstream returned non-JSON (HTML error page or empty body)
raise HTTPException(status_code=502, detail=f"Upstream returned non-JSON at {url}: {r.status_code} {r.text[:1000]}")
async def _post_file(client: httpx.AsyncClient, url: str, data: bytes, fields: Dict[str, Any]) -> Dict[str, Any]: async def _post_file(client: httpx.AsyncClient, url: str, data: bytes, fields: Dict[str, Any]) -> Dict[str, Any]:
files = {"file": ("image", data, "application/octet-stream")} files = {"file": ("image", data, "application/octet-stream")}
r = await client.post(url, data={k: str(v) for k, v in fields.items()}, files=files) r = await client.post(url, data={k: str(v) for k, v in fields.items()}, files=files)
if r.status_code >= 400: if r.status_code >= 400:
raise HTTPException(status_code=502, detail=f"Upstream error {url}: {r.status_code} {r.text[:200]}") raise HTTPException(status_code=502, detail=f"Upstream error {url}: {r.status_code} {r.text[:1000]}")
return r.json() try:
return r.json()
except Exception:
raise HTTPException(status_code=502, detail=f"Upstream returned non-JSON at {url}: {r.status_code} {r.text[:1000]}")
@app.get("/health") @app.get("/health")