Skip to content
Clone
7f01cd4
61 lines 1.5 KB
import type { ApiErrorBody } from './types'
export class AgentSdkError extends Error {
readonly status: number | undefined
readonly code: string | undefined
readonly retryAfterMs: number | undefined
readonly body: string | undefined
constructor(
message: string,
options: {
status?: number
code?: string
retryAfterMs?: number
body?: string
cause?: unknown
} = {},
) {
super(message, options.cause === undefined ? undefined : { cause: options.cause })
this.name = 'AgentSdkError'
this.status = options.status
this.code = options.code
this.retryAfterMs = options.retryAfterMs
this.body = options.body
}
get isUnauthorized(): boolean {
return this.status === 401
}
get isForbidden(): boolean {
return this.status === 403
}
get isNotFound(): boolean {
return this.status === 404
}
get isRetryable(): boolean {
if (this.status === undefined) return true
if (this.status === 429) return true
return this.status >= 500
}
}
export async function errorFromResponse(response: Response): Promise<AgentSdkError> {
const body = await response.text().catch(() => '')
let parsed: ApiErrorBody | undefined
try {
parsed = JSON.parse(body) as ApiErrorBody
} catch {
parsed = undefined
}
const message = parsed?.message ?? body.trim() ?? response.statusText
return new AgentSdkError(message, {
status: response.status,
code: parsed?.code,
retryAfterMs: parsed?.retry_after_ms,
body,
})
}