{"record":{"id":"a0dfccce6521a5bf","repo":"linshenkx/prompt-optimizer","slug":"connection-failed-error-message","errorCode":null,"errorMessage":"Connection failed: ${error.message}","messagePattern":"Connection failed: (.+?)","errorType":"exception","errorClass":"APIError","httpStatus":null,"severity":"error","filePath":"packages/core/src/services/llm/adapters/openai-adapter.ts","lineNumber":177,"sourceCode":"          throw new APIError('API returned empty model list')\n        }\n\n        return models\n      }\n\n      throw new APIError('Unexpected API response format')\n    } catch (error: any) {\n      console.error('[OpenAIAdapter] Failed to fetch models:', error)\n\n      // 连接错误处理（包括跨域检测）\n      if (error.message && (error.message.includes('Failed to fetch') ||\n          error.message.includes('Connection error'))) {\n        const isCrossOriginError = this.detectCrossOriginError(error, baseURL)\n\n        if (isCrossOriginError) {\n          throw new APIError(`Cross-origin connection failed: ${error.message}`)\n        } else {\n          throw new APIError(`Connection failed: ${error.message}`)\n        }\n      }\n\n      // API返回的错误信息\n      if (error.response?.data) {\n        throw new APIError(`API error: ${JSON.stringify(error.response.data)}`)\n      }\n\n      // 其他错误,保持原始信息\n      throw new APIError(error.message || 'Unknown error')\n    }\n  }\n\n  // ===== 参数定义（用于buildDefaultModel） =====\n\n  /**\n   * 获取参数定义\n   * 基于 OpenAI 官方文档: https://platform.openai.com/docs/api-reference/chat/create","sourceCodeStart":159,"sourceCodeEnd":195,"githubUrl":"https://github.com/linshenkx/prompt-optimizer/blob/3e677b1d9f7e0493c142c175560531e7ae786dce/packages/core/src/services/llm/adapters/openai-adapter.ts#L159-L195","documentation":"Same network-failure branch as the CORS case, but detectCrossOriginError concluded it is a plain connectivity failure — the endpoint is unreachable, refused, or DNS fails, and it's not a cross-origin browser block. Message is prefixed 'Connection failed:'.","triggerScenarios":"getModelsAsync() against a local server that isn't running (ECONNREFUSED), wrong port, DNS failure for the base URL host, TLS errors, or no network.","commonSituations":"Gateway process stopped, wrong port in baseURL, typo in hostname, VPN/offline machine, server restarting.","solutions":["Confirm the server is running: curl $BASE_URL/models from the same environment","Fix scheme/port/typos in baseURL (http vs https, correct port)","If server-side, add reachability checks/retry with backoff for transient failures","Check DNS/firewall/VPN if the host should be reachable"],"exampleFix":"// before\nconst models = await adapter.getModelsAsync()\n\n// after\nif (!(await isReachable(baseURL))) throw new Error(`LLM endpoint ${baseURL} unreachable`)\nconst models = await adapter.getModelsAsync()","handlingStrategy":"retry","validationCode":"async function endpointReachable(baseURL: string): Promise<boolean> {\n  try { const u = new URL(baseURL); await fetch(u.origin, { mode: 'no-cors' }); return true } catch { return false }\n}","typeGuard":"function isConnectionFailure(e: unknown): boolean {\n  return e instanceof APIError && e.message.startsWith('Connection failed')\n}","tryCatchPattern":"try { models = await adapter.getModelsAsync() }\ncatch (e) {\n  if (isConnectionFailure(e)) return withBackoff(() => adapter.getModelsAsync(), 3)\n  throw e\n}","preventionTips":["Health-check configured endpoints at app startup","Double-check scheme, host and port in baseURL","Supervise local gateway processes (restart on crash)"],"tags":["network","connection","openai","endpoint-unreachable"],"backgroundTag":"endpoint-unreachable","analyzedSha":"3e677b1d9f7e0493c142c175560531e7ae786dce","analyzedAt":"2026-08-27T21:29:16.709Z","schemaVersion":2},"datasetVersion":"2026-08-28T00:17:15.603Z"}