PHP 代码优化:使用数组和循环处理 GPT API 错误
使用数组和循环优化 GPT API 错误处理
在使用 GPT API 时,经常会遇到一些错误信息,例如 'limit reached for default-gpt-3.5-turbo'、'301 Moved Permanently' 等。为了简化代码并提高可读性,我们可以使用数组和循环来处理这些错误。
原代码:
if (strpos($article_gpt, 'limit reached for default-gpt-3.5-turbo') !== false) {
exit;
}
if (strpos($article_gpt, '301 Moved Permanently') !== false) {
exit;
}
if (strpos($article_gpt, 'server had an error while processing your request') !== false) {
exit;
}
if (strpos($article_gpt, 'model is currently overloaded with other requests') !== false) {
exit;
}
if (strpos($article_gpt, '502 Bad Gateway') !== false) {
exit;
}
优化后的代码:
$errors = [
'limit reached for default-gpt-3.5-turbo',
'301 Moved Permanently',
'server had an error while processing your request',
'model is currently overloaded with other requests',
'502 Bad Gateway'
];
foreach ($errors as $error) {
if (strpos($article_gpt, $error) !== false) {
exit;
}
}
优点:
- 使用数组存储错误信息,减少重复代码。
- 代码更简洁易读。
- 如果需要增加或修改错误信息,只需要修改数组即可。
通过这种优化,我们可以更有效地处理 GPT API 错误,提高代码的可读性和维护性。
原文地址: https://www.cveoy.top/t/topic/qk6t 著作权归作者所有。请勿转载和采集!