错误处理增强
为代码添加健壮的错误处理
提示词
请为以下代码添加健壮的错误处理:
`
[粘贴代码]
`
要求:
1. 识别可能出错的地方(网络请求、文件IO、类型转换等)
2. 添加try-catch/错误返回
3. 有意义的错误信息
4. 重试机制(对可重试错误)
5. 日志记录
6. 优雅降级方案
7. 用户友好的错误提示示例输出
async function fetchUser(userId) {
// 参数校验
if (!userId || typeof userId !== 'number') {
throw new Error('Invalid userId: must be a number');
}
try {
const response = await fetchWithRetry(
`/api/users/${userId}`,
{ retries: 3, delay: 1000 }
);
if (!response.ok) {
if (response.status === 404) return null;
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
logger.error(`Failed to fetch user ${userId}:`, error);
// 降级:返回缓存数据或null
return cache.get(`user:${userId}`) ?? null;
}
}评论 0
更多
登录后可点赞、收藏、评论和举报。
还没有评论,先发起一个具体问题。