fix(insights): map LLM-parse failure to 422 instead of 502

Same Cloudflare-rewrites-5xx footgun the v1.4.5 ai/test fix solved. A
malformed JSON response from the upstream model returned HTTP 502, which
Cloudflare swapped for its own HTML error page; the client's
`await res.json()` then crashed with `Unexpected token '<', "<!DOCTYPE "`
and the user — already throttled by the 2/h rate limit — saw nothing
useful. 4xx passes through Cloudflare untouched, so the React Query
mutation can read the JSON envelope and show a real error.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Marc-André BombeckandClaude Opus 4.7 committed 2026-05-09 01:27:07 +02:00
1 parent eba898f4c1
commit c8ee28d2b0
1 file changed
+5 -1
+5 -1
View File
@@ -82,7 +82,11 @@ export const POST = apiHandler(async (request: NextRequest) => {
const validated = insightResultSchema.safeParse(parsed);
insights = validated.success ? validated.data : parsed;
} catch {
return apiError("Failed to parse AI response", 502);
// Returning 502 here triggers Cloudflare's HTML error rewrite, which
// breaks `await res.json()` on the client side. 422 stays passthrough
// so the React Query mutation can read the JSON body and surface a
// readable message. Same fix pattern as v1.4.5 ai/test.
return apiError("AI response was not valid JSON", 422);
}
await prisma.user.update({