forked from CherryHQ/cherry-studio-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.ts
More file actions
294 lines (251 loc) · 9.43 KB
/
error.ts
File metadata and controls
294 lines (251 loc) · 9.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
import type { NoSuchToolError } from 'ai'
import { InvalidToolInputError } from 'ai'
import { t } from 'i18next'
import type { z } from 'zod'
import type {
AiSdkErrorUnion,
SerializedAiSdkError,
SerializedAiSdkInvalidToolInputError,
SerializedAiSdkNoSuchToolError,
SerializedError
} from '@/types/error'
import { isSerializedAiSdkAPICallError } from '@/types/error'
import { safeSerialize } from './serialize'
// const logger = loggerService.withContext('Utils:error')
export function getErrorDetails(err: any, seen = new WeakSet()): any {
// Handle circular references
if (err === null || typeof err !== 'object' || seen.has(err)) {
return err
}
seen.add(err)
const result: any = {}
// Get all enumerable properties, including those from the prototype chain
const allProps = new Set([...Object.getOwnPropertyNames(err), ...Object.keys(err)])
for (const prop of allProps) {
try {
const value = err[prop]
// Skip function properties
if (typeof value === 'function') continue
// Recursively process nested objects
result[prop] = getErrorDetails(value, seen)
} catch {
result[prop] = '<Unable to access property>'
}
}
return result
}
export function formatErrorMessage(error: any): string {
try {
const detailedError = getErrorDetails(error)
delete detailedError?.headers
delete detailedError?.stack
delete detailedError?.request_id
const formattedJson = JSON.stringify(detailedError, null, 2)
.split('\n')
.map(line => ` ${line}`)
.join('\n')
return `Error Details:\n${formattedJson}`
} catch {
try {
return `Error: ${String(error)}`
} catch {
return 'Error: Unable to format error message'
}
}
}
export const isAbortError = (error: any): boolean => {
// Convert message to string for consistent checking
const errorMessage = String(error?.message || '')
// 检查错误消息
if (errorMessage === 'Request was aborted.') {
return true
}
// 检查是否为 DOMException 类型的中止错误
if (error instanceof DOMException && error.name === 'AbortError') {
return true
}
// 检查 OpenAI 特定的错误结构
if (
error &&
typeof error === 'object' &&
errorMessage &&
(errorMessage === 'Request was aborted.' || errorMessage.includes('signal is aborted without reason'))
) {
return true
}
return false
}
export const formatMcpError = (error: any) => {
if (error.message.includes('32000')) {
return t('settings.mcp.errors.32000')
}
return error.message
}
const getBaseError = (error: Error) => {
return {
name: error.name ?? null,
message: error.message ?? null,
stack: error.stack ?? null,
cause: error.cause ? String(error.cause) : null
} as const
}
const serializeInvalidToolInputError = (error: InvalidToolInputError): SerializedAiSdkInvalidToolInputError => {
const baseError = getBaseError(error)
return {
...baseError,
toolName: error.toolName,
toolInput: error.toolInput
} satisfies SerializedAiSdkInvalidToolInputError
}
const serializeNoSuchToolError = (error: NoSuchToolError): SerializedAiSdkNoSuchToolError => {
const baseError = getBaseError(error)
return {
...baseError,
toolName: error.toolName ?? null,
availableTools: error.availableTools ?? null
} satisfies SerializedAiSdkNoSuchToolError
}
export const serializeError = (error: AiSdkErrorUnion): SerializedError => {
// 统一所有可能的错误字段
const serializedError: SerializedError = {
name: error.name ?? null,
message: error.message ?? null,
stack: error.stack ?? null,
cause: safeSerialize(error.cause)
}
if ('url' in error) serializedError.url = error.url
if ('requestBodyValues' in error) serializedError.requestBodyValues = safeSerialize(error.requestBodyValues)
if ('statusCode' in error) serializedError.statusCode = error.statusCode ?? null
if ('responseBody' in error) serializedError.responseBody = error.responseBody ?? null
if ('isRetryable' in error) serializedError.isRetryable = error.isRetryable
if ('data' in error) serializedError.data = safeSerialize(error.data)
if ('responseHeaders' in error) serializedError.responseHeaders = error.responseHeaders ?? null
if ('statusText' in error) serializedError.statusText = error.statusText ?? null
if ('parameter' in error) serializedError.parameter = error.parameter
if ('value' in error) serializedError.value = safeSerialize(error.value)
if ('content' in error) serializedError.content = safeSerialize(error.content)
if ('role' in error) serializedError.role = error.role
if ('prompt' in error) serializedError.prompt = safeSerialize(error.prompt)
if ('toolName' in error) serializedError.toolName = error.toolName
if ('toolInput' in error) serializedError.toolInput = error.toolInput
if ('text' in error) serializedError.text = error.text ?? null
if ('originalMessage' in error) serializedError.originalMessage = safeSerialize(error.originalMessage)
if ('response' in error) serializedError.response = error.response ?? null
if ('usage' in error) serializedError.usage = safeSerialize(error.usage)
if ('finishReason' in error) serializedError.finishReason = error.finishReason ?? null
if ('modelId' in error) serializedError.modelId = error.modelId
if ('modelType' in error) serializedError.modelType = error.modelType
if ('providerId' in error) serializedError.providerId = error.providerId
if ('availableProviders' in error) serializedError.availableProviders = error.availableProviders
if ('availableTools' in error) serializedError.availableTools = error.availableTools ?? null
if ('reason' in error) serializedError.reason = error.reason
if ('lastError' in error) serializedError.lastError = safeSerialize(error.lastError)
if ('errors' in error) serializedError.errors = error.errors.map((err: unknown) => safeSerialize(err))
if ('originalError' in error)
serializedError.originalError = InvalidToolInputError.isInstance(error.originalError)
? serializeInvalidToolInputError(error.originalError)
: serializeNoSuchToolError(error.originalError)
if ('functionality' in error) serializedError.functionality = error.functionality
return serializedError
}
/**
* 格式化 Zod 验证错误信息为可读的字符串
* @param error - Zod 验证错误对象
* @param title - 可选的错误标题,会作为前缀添加到错误信息中
* @returns 格式化后的错误信息字符串。
*/
export const formatZodError = (error: z.ZodError, title?: string) => {
const readableErrors = error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`)
const errorMessage = readableErrors.join('\n')
return title ? `${title}: \n${errorMessage}` : errorMessage
}
/**
* 将任意值安全地转换为字符串
* @param value - 需要转换的值,unknown 类型
* @returns 转换后的字符串
*
* @description
* 该函数可以安全地处理以下情况:
* - null 和 undefined 会被转换为 'null'
* - 字符串直接返回
* - 原始类型(数字、布尔值、bigint等)使用 String() 转换
* - 对象和数组会尝试使用 JSON.stringify 序列化,并处理循环引用
* - 如果序列化失败,返回错误信息
*
* @example
* ```ts
* safeToString(null) // 'null'
* safeToString('test') // 'test'
* safeToString(123) // '123'
* safeToString({a: 1}) // '{"a":1}'
* ```
*/
export function safeToString(value: unknown): string {
// 处理 null 和 undefined
if (value == null) {
return 'null'
}
// 字符串直接返回
if (typeof value === 'string') {
return value
}
// 数字、布尔值、bigint 等原始类型,安全用 String()
if (typeof value !== 'object' && typeof value !== 'function') {
return String(value)
}
// 处理对象(包括数组)
if (typeof value === 'object') {
// 处理函数
if (typeof value === 'function') {
return value.toString()
}
// 其他对象
try {
return JSON.stringify(value, getCircularReplacer())
} catch (err) {
return '[Unserializable: ' + err + ']'
}
}
return String(value)
}
// 防止循环引用导致的 JSON.stringify 崩溃
function getCircularReplacer() {
const seen = new WeakSet()
return (_key: string, value: unknown) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]'
}
seen.add(value)
}
return value
}
}
export function formatError(error: SerializedError): string {
return `${t('error.name')}: ${error.name}\n${t('error.message')}: ${error.message}\n${t('error.stack')}: ${error.stack}`
}
export function formatAiSdkError(error: SerializedAiSdkError): string {
let text = formatError(error) + '\n'
if (error.cause) {
text += `${t('error.cause')}: ${error.cause}\n`
}
if (isSerializedAiSdkAPICallError(error)) {
if (error.statusCode) {
text += `${t('error.statusCode')}: ${error.statusCode}\n`
}
text += `${t('error.requestUrl')}: ${error.url}\n`
const requestBodyValues = safeToString(error.requestBodyValues)
text += `${t('error.requestBodyValues')}: ${requestBodyValues}\n`
if (error.responseHeaders) {
text += `${t('error.responseHeaders')}: ${JSON.stringify(error.responseHeaders, null, 2)}\n`
}
if (error.responseBody) {
text += `${t('error.responseBody')}: ${error.responseBody}\n`
}
if (error.data) {
const data = safeToString(error.data)
text += `${t('error.data')}: ${data}\n`
}
}
return text.trim()
}