Improve OpenAI/OpenRouter error parsing

This commit is contained in:
Cohee 2023-08-08 20:07:41 +03:00
parent 9a7654598e
commit c94eae6eb6

View File

@ -3327,7 +3327,22 @@ app.post("/generate_openai", jsonParser, function (request, response_generate_op
makeRequest(config, response_generate_openai, request, retries - 1); makeRequest(config, response_generate_openai, request, retries - 1);
}, timeout); }, timeout);
} else { } else {
handleError(error, response_generate_openai, request); let errorData = error.response.data;
if (request.body.stream) {
try {
const chunks = await readAllChunks(errorData);
const blob = new Blob(chunks, { type: 'application/json' });
const text = await blob.text();
errorData = JSON.parse(text);
} catch {
console.warn('Error parsing streaming response');
}
} else {
errorData = typeof errorData === 'string' ? tryParse(errorData) : errorData;
}
handleError(error, response_generate_openai, errorData);
} }
} }
} }
@ -3339,27 +3354,28 @@ app.post("/generate_openai", jsonParser, function (request, response_generate_op
} }
} }
function handleError(error, response_generate_openai, request) { function handleError(error, response_generate_openai, errorData) {
console.error('Error:', error.message); console.error('Error:', error.message);
let message = error?.response?.statusText; let message = error?.response?.statusText;
switch (error?.response?.status) { const statusMessages = {
case 402: 400: 'Bad request',
message = error?.response?.data?.error?.message || 'Credit limit reached'; 401: 'Unauthorized',
console.log(message); 402: 'Credit limit reached',
break; 403: 'Forbidden',
case 403: 404: 'Not found',
message = error?.response?.data?.error?.message || 'API key disabled or exhausted'; 429: 'Too many requests',
console.log(message); 451: 'Unavailable for legal reasons',
break; };
case 451:
message = error?.response?.data?.error?.message || 'Unavailable for legal reasons'; const status = error?.response?.status;
console.log(message); if (statusMessages.hasOwnProperty(status)) {
break; message = errorData?.error?.message || statusMessages[status];
console.log(message);
} }
const quota_error = error?.response?.status === 429 && error?.response?.data?.error?.type === 'insufficient_quota'; const quota_error = error?.response?.status === 429 && errorData?.error?.type === 'insufficient_quota';
const response = { error: { message }, quota_error: quota_error } const response = { error: { message }, quota_error: quota_error }
if (!response_generate_openai.headersSent) { if (!response_generate_openai.headersSent) {
response_generate_openai.send(response); response_generate_openai.send(response);