Files
dify/web/utils/error-parser.ts
T

47 lines
1.6 KiB
TypeScript
Raw Normal View History

+3
2025-11-12 17:59:37 +08:00
/**
* Parse plugin error message from nested error structure
* Extracts the real error message from PluginInvokeError JSON string
*
* @example
* Input: { message: "req_id: xxx PluginInvokeError: {\"message\":\"Bad credentials\"}" }
* Output: "Bad credentials"
*
* @param error - Error object (can be Response object or error with message property)
* @returns Promise<string> or string - Parsed error message
*/
export const parsePluginErrorMessage = async (error: any): Promise<string> => {
let rawMessage = ''
// Handle Response object from fetch/ky
if (error instanceof Response) {
try {
const body = await error.clone().json()
rawMessage = body?.message || error.statusText || 'Unknown error'
2026-07-12 23:57:46 +08:00
} catch {
+3
2025-11-12 17:59:37 +08:00
rawMessage = error.statusText || 'Unknown error'
}
2026-07-12 23:57:46 +08:00
} else {
+3
2025-11-12 17:59:37 +08:00
rawMessage = error?.message || error?.toString() || 'Unknown error'
}
console.log('rawMessage', rawMessage)
// Try to extract nested JSON from PluginInvokeError
// Use greedy match .+ to capture the complete JSON object with nested braces
const pluginErrorPattern = /PluginInvokeError:\s*(\{.+\})/
const match = pluginErrorPattern.exec(rawMessage)
+3
2025-11-12 17:59:37 +08:00
if (match) {
try {
const errorData = JSON.parse(match[1]!)
+3
2025-11-12 17:59:37 +08:00
// Return the inner message if exists
2026-07-12 23:57:46 +08:00
if (errorData.message) return errorData.message
+3
2025-11-12 17:59:37 +08:00
// Fallback to error_type if message not available
2026-07-12 23:57:46 +08:00
if (errorData.error_type) return errorData.error_type
} catch (parseError) {
+3
2025-11-12 17:59:37 +08:00
console.warn('Failed to parse plugin error JSON:', parseError)
}
}
return rawMessage
}