fix: 改进RMBG API错误处理 - 添加超时控制和网络连接错误提示
This commit is contained in:
parent
997afdd694
commit
30a0c09cf3
@ -187,11 +187,63 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
const startTime = Date.now();
|
||||
const response = await fetch(apiUrl, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(requestBody),
|
||||
});
|
||||
let response: Response;
|
||||
|
||||
try {
|
||||
// 添加超时控制(30秒)
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 30000);
|
||||
|
||||
response = await fetch(apiUrl, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: JSON.stringify(requestBody),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
} catch (fetchError) {
|
||||
const processingTime = (Date.now() - startTime) / 1000;
|
||||
console.error("[RMBG API] 网络请求失败:", {
|
||||
error: fetchError,
|
||||
apiUrl,
|
||||
processingTime,
|
||||
});
|
||||
|
||||
// 检查是否是网络连接错误
|
||||
if (fetchError instanceof Error) {
|
||||
if (fetchError.name === 'AbortError') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "抠图API请求超时",
|
||||
detail: "请求超过30秒未响应,请检查API服务器状态或网络连接",
|
||||
},
|
||||
{ status: 504 }
|
||||
);
|
||||
}
|
||||
|
||||
if (fetchError.message.includes('EHOSTUNREACH') ||
|
||||
fetchError.message.includes('ENOTFOUND') ||
|
||||
fetchError.message.includes('ECONNREFUSED') ||
|
||||
fetchError.message.includes('No route to host')) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "无法连接到抠图API服务器",
|
||||
detail: `服务器无法访问 ${apiUrl},请检查:\n1. API服务器是否在线\n2. 网络连接是否正常\n3. 防火墙设置是否正确`,
|
||||
},
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "抠图API请求失败",
|
||||
detail: fetchError instanceof Error ? fetchError.message : "未知网络错误",
|
||||
},
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
|
||||
const processingTime = (Date.now() - startTime) / 1000;
|
||||
|
||||
@ -201,6 +253,7 @@ export async function POST(request: NextRequest) {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: errorText,
|
||||
apiUrl,
|
||||
});
|
||||
|
||||
return NextResponse.json(
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user