fix: better handle for RetryError

This commit is contained in:
AnotiaWang
2025-03-09 22:50:55 +08:00
parent e5b3cdda76
commit 5e3eb5fc9b

View File

@ -1,10 +1,6 @@
import { APICallError } from 'ai'
import { APICallError, RetryError } from 'ai'
/**
* Parse an error thrown by the AI SDK, and re-throw it with a human-readable message
*/
export function throwAiError(operation: string, error: unknown) {
if (APICallError.isInstance(error)) {
function handleApiCallError(operation: string, error: APICallError) {
let message = error.message
if (error.statusCode) message += ` (${error.statusCode})`
if (error.cause) message += `\nCause: ${error.cause}`
@ -20,6 +16,35 @@ export function throwAiError(operation: string, error: unknown) {
url: error.url,
})
throw new Error(message)
}
function handleRetryError(operation: string, error: RetryError) {
if (APICallError.isInstance(error.lastError)) {
handleApiCallError(operation, error.lastError)
}
let message = error.message
if (error.cause) message += `\nCause: ${error.cause}`
if (error.stack) message += `\nStack: ${error.stack}`
if (error.reason) message += `\nReason: ${error.reason}`
console.error(`[${operation}]`, error, {
cause: error.cause,
stack: error.stack,
lastError: error.lastError,
reason: error.reason,
errors: error.errors,
})
throw new Error(message)
}
/**
* Parse an error thrown by the AI SDK, and re-throw it with a human-readable message
*/
export function throwAiError(operation: string, error: unknown) {
if (APICallError.isInstance(error)) {
handleApiCallError(operation, error)
} else if (RetryError.isInstance(error)) {
handleRetryError(operation, error)
} else {
console.error(`[${operation}]`, error)
}