优雅处理API错误的最佳实践
// 完整的错误处理示例
class APIError extends Error {
constructor(message, status, code) {
super(message);
this.status = status;
this.code = code;
}
}
async function handleAPICall() {
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ /* ... */ })
});
if (!response.ok) {
const error = await response.json();
switch (response.status) {
case 400:
throw new APIError('请求参数错误', 400, error.code);
case 401:
throw new APIError('认证失败', 401, error.code);
case 429:
throw new APIError('请求过于频繁', 429, error.code);
case 500:
throw new APIError('服务器错误', 500, error.code);
default:
throw new APIError('未知错误', response.status, error.code);
}
}
return await response.json();
} catch (error) {
console.error('API调用失败:', error);
// 记录日志、显示用户友好的错误信息等
throw error;
}
}5分钟内完成接入
遵循推荐的开发模式
获取专业帮助