refactor(console): simplify provider error parsing

This commit is contained in:
opencode-agent[bot] 2026-06-02 13:54:04 +00:00
commit 8378856a90
2 changed files with 18 additions and 18 deletions

View file

@ -48,7 +48,7 @@ import { localeFromRequest } from "~/lib/language"
import { createModelTpmLimiter } from "./modelTpmLimiter"
import { createModelTpsLimiter } from "./modelTpsLimiter"
import { accumulateUsage, HOT_WORKSPACES } from "./usageBatcher"
import { readProviderError } from "./providerError"
import { parseProviderErrorBody } from "./providerError"
type ZenData = Awaited<ReturnType<typeof ZenData.list>>
type RetryOptions = {
@ -249,7 +249,15 @@ export async function handler(
// Handle non-streaming response
if (!isStream || [400, 404, 429].includes(res.status)) {
const json = res.status === 200 ? await res.json() : await readProviderError(res)
const json = await (async () => {
if (res.status === 200) return res.json()
const body = await res.text()
try {
const parsed = JSON.parse(body)
if (parsed && typeof parsed === "object") return parsed as Record<string, any>
} catch {}
return parseProviderErrorBody(body, res.statusText)
})()
await rateLimiter?.track()
const usage = providerInfo.extractUsage(json)
if (usage) {

View file

@ -1,10 +1,3 @@
export async function readProviderError(res: Response) {
const body = await res.text()
const json = parseJson(body)
if (json && typeof json === "object") return json as Record<string, any>
return parseProviderErrorBody(body, res.statusText)
}
export function parseProviderErrorBody(body: string, statusText: string) {
const text = body.trim()
const sseData = text
@ -14,7 +7,14 @@ export function parseProviderErrorBody(body: string, statusText: string) {
.map((line) => line.slice(5).trim())
.filter((line) => line && line !== "[DONE]")
const parsed = sseData.map(parseJson).find((item) => item && typeof item === "object")
const parsed = (() => {
for (const data of sseData) {
try {
const json = JSON.parse(data)
if (json && typeof json === "object") return json as Record<string, any>
} catch {}
}
})()
if (parsed) return parsed as Record<string, any>
return {
@ -23,11 +23,3 @@ export function parseProviderErrorBody(body: string, statusText: string) {
},
}
}
function parseJson(value: string) {
try {
return JSON.parse(value) as unknown
} catch {
return undefined
}
}