[ PROMPT_NODE_23754 ]
异步模式与错误处理
[ SKILL_DOCUMENTATION ]
# 异步模式与错误处理
关于 async/await 模式及自定义错误处理的完整指南。
## 目录
- [Async/Await 最佳实践](#asyncawait-最佳实践)
- [Promise 错误处理](#promise-错误处理)
- [自定义错误类型](#自定义错误类型)
- [asyncErrorWrapper 工具](#asyncerrorwrapper-工具)
- [错误传播](#错误传播)
- [常见的异步陷阱](#常见的异步陷阱)
---
## Async/Await 最佳实践
### 始终使用 Try-Catch
typescript
// ❌ 错误:未处理的异步错误
async function fetchData() {
const data = await database.query(); // 如果抛出异常,则未被捕获!
return data;
}
// ✅ 正确:使用 try-catch 包裹
async function fetchData() {
try {
const data = await database.query();
return data;
} catch (error) {
Sentry.captureException(error);
throw error;
}
}
### 避免使用 .then() 链式调用
typescript
// ❌ 避免:Promise 链
function processData() {
return fetchData()
.then(data => transform(data))
.then(transformed => save(transformed))
.catch(error => {
console.error(error);
});
}
// ✅ 推荐:使用 Async/await
async function processData() {
try {
const data = await fetchData();
const transformed = await transform(data);
return await save(transformed);
} catch (error) {
Sentry.captureException(error);
throw error;
}
}
---
## Promise 错误处理
### 并行操作
typescript
// ✅ 在 Promise.all 中处理错误
try {
const [users, profiles, settings] = await Promise.all([
userService.getAll(),
profileService.getAll(),
settingsService.getAll(),
]);
} catch (error) {
// 其中一个失败则全部失败
Sentry.captureException(error);
throw error;
}
// ✅ 使用 Promise.allSettled 单独处理错误
const results = await Promise.allSettled([
userService.getAll(),
profileService.getAll(),
settingsService.getAll(),
]);
results.forEach((result, index) => {
if (result.status === 'rejected') {
Sentry.captureException(result.reason, {
tags: { operation: ['users', 'profiles', 'settings'][index] }
});
}
});
---
## 自定义错误类型
### 定义自定义错误
typescript
// 基础错误类
export class AppError extends Error {
constructor(
message: string,
public code: string,
public statusCode: number,
publi