-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patherror-handling.ts
More file actions
458 lines (378 loc) · 12.4 KB
/
Copy patherror-handling.ts
File metadata and controls
458 lines (378 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
#!/usr/bin/env tsx
import type { TaskInput } from "../src/workflow/Task";
import { DAGTask, WorkflowBuilder } from "../src/workflow/WorkflowBuilder";
/**
* 🛡️ 错误处理示例
*
* 本示例展示:
* 1. 任务失败处理
* 2. 错误恢复策略
* 3. 超时处理
* 4. 回退机制
* 5. 错误监控和日志
*/
// 🔥 可能失败的网络请求任务
class NetworkRequestTask extends DAGTask {
name = "networkRequest";
constructor(
private failureRate = 0.3,
dependencies: DAGTask[] = [],
) {
super(dependencies);
}
async execute(input: TaskInput): Promise<Record<string, any>> {
console.log("🌐 正在发起网络请求...");
// 模拟网络延迟
await new Promise((resolve) => setTimeout(resolve, 600));
// 模拟随机失败
if (Math.random() < this.failureRate) {
throw new Error("网络请求失败: 连接超时");
}
const networkData = {
status: "success",
data: { users: 150, activeConnections: 45 },
timestamp: Date.now(),
};
console.log("✅ 网络请求成功");
return { ...input, networkData };
}
}
// ⏰ 超时任务
class SlowProcessingTask extends DAGTask {
name = "slowProcessing";
constructor(
private duration = 2000,
dependencies: DAGTask[] = [],
) {
super(dependencies);
}
async execute(input: TaskInput): Promise<Record<string, any>> {
console.log("⏳ 正在执行耗时处理...");
// 模拟长时间处理
await new Promise((resolve) => setTimeout(resolve, this.duration));
console.log("✅ 耗时处理完成");
return {
...input,
processedData: {
result: "complex_calculation_result",
processingTime: this.duration,
},
};
}
}
// 💾 数据库操作任务
class DatabaseOperationTask extends DAGTask {
name = "databaseOperation";
constructor(
private shouldFail = false,
dependencies: DAGTask[] = [],
) {
super(dependencies);
}
async execute(input: TaskInput): Promise<Record<string, any>> {
console.log("💾 正在执行数据库操作...");
await new Promise((resolve) => setTimeout(resolve, 400));
if (this.shouldFail) {
throw new Error("数据库连接失败: 无法连接到主数据库");
}
console.log("✅ 数据库操作成功");
return {
...input,
dbResult: {
recordsUpdated: 25,
operation: "batch_update",
},
};
}
}
// 🔄 重试任务
class RetryableTask extends DAGTask {
name = "retryableTask";
private attemptCount = 0;
constructor(
private maxAttempts = 3,
dependencies: DAGTask[] = [],
) {
super(dependencies);
}
async execute(input: TaskInput): Promise<Record<string, any>> {
this.attemptCount++;
console.log(`🔄 重试任务执行 (第${this.attemptCount}次尝试)`);
await new Promise((resolve) => setTimeout(resolve, 300));
// 前两次尝试失败,第三次成功
if (this.attemptCount < this.maxAttempts) {
throw new Error(`第${this.attemptCount}次尝试失败`);
}
console.log("✅ 重试任务最终成功");
return {
...input,
retryResult: {
attempts: this.attemptCount,
finalResult: "success_after_retry",
},
};
}
}
// 🚨 紧急备用任务
class FallbackTask extends DAGTask {
name = "fallbackTask";
constructor(dependencies: DAGTask[] = []) {
super(dependencies);
}
async execute(input: TaskInput): Promise<Record<string, any>> {
console.log("🚨 执行备用方案...");
await new Promise((resolve) => setTimeout(resolve, 200));
const fallbackData = {
source: "fallback",
data: { message: "使用缓存数据或默认值" },
reliability: "medium",
};
console.log("✅ 备用方案执行完成");
return { ...input, fallbackData };
}
}
// 🔧 错误恢复任务
class ErrorRecoveryTask extends DAGTask {
name = "errorRecovery";
constructor(dependencies: DAGTask[] = []) {
super(dependencies);
}
async execute(input: TaskInput): Promise<Record<string, any>> {
console.log("🔧 正在执行错误恢复...");
await new Promise((resolve) => setTimeout(resolve, 500));
const recoveryActions = [
"清理临时文件",
"重置连接池",
"发送错误报告",
"切换到备用服务器",
];
console.log("✅ 错误恢复完成");
return {
...input,
recoveryResult: {
actions: recoveryActions,
status: "recovered",
timestamp: Date.now(),
},
};
}
}
// 📊 健康检查任务
class HealthCheckTask extends DAGTask {
name = "healthCheck";
constructor(dependencies: DAGTask[] = []) {
super(dependencies);
}
async execute(input: TaskInput): Promise<Record<string, any>> {
console.log("📊 正在执行系统健康检查...");
await new Promise((resolve) => setTimeout(resolve, 300));
const healthStatus = {
system: "healthy",
services: {
database: "online",
cache: "online",
external_api: "degraded",
},
metrics: {
cpu: "45%",
memory: "62%",
disk: "78%",
},
};
console.log("✅ 健康检查完成");
return { ...input, healthStatus };
}
}
// 📝 错误日志任务
class ErrorLoggingTask extends DAGTask {
name = "errorLogging";
constructor(dependencies: DAGTask[] = []) {
super(dependencies);
}
async execute(input: TaskInput): Promise<Record<string, any>> {
console.log("📝 正在记录错误日志...");
const errorLog = {
timestamp: new Date().toISOString(),
errorCount: 1,
errorTypes: ["NetworkError"],
severity: "medium",
actionsTaken: ["fallback_executed", "error_recovery_initiated"],
};
console.log("✅ 错误日志记录完成");
return { ...input, errorLog };
}
}
// 🎯 主函数 - 运行错误处理示例
async function runErrorHandlingExample() {
console.log("🛡️ 开始运行错误处理示例\n");
try {
// 示例1: 基础错误处理和恢复
console.log("🎯 示例1: 基础错误处理和恢复");
console.log("=".repeat(50));
const basicWorkflow = WorkflowBuilder.create()
.addTask(new NetworkRequestTask(0.8)) // 80% 失败率
.addTask(new DatabaseOperationTask(false))
// 网络请求失败时启用备用方案
.addDynamicStrategy({
name: "network_fallback",
condition: (context) => {
const lastError = context.get("lastError");
return !!(
lastError &&
typeof lastError === "string" &&
lastError.includes("网络请求失败")
);
},
generator: async (context) => {
console.log("🚨 检测到网络失败,启动备用方案");
return [new FallbackTask()];
},
priority: 10,
once: true,
})
// 任何失败时执行错误恢复
.addDynamicStrategy({
name: "error_recovery",
condition: (context) => context.get("hasError") === true,
generator: async (context) => {
console.log("🔧 检测到系统错误,启动恢复流程");
return [new ErrorRecoveryTask(), new ErrorLoggingTask()];
},
priority: 5,
})
.withConfig({
retryAttempts: 2,
timeoutMs: 5000,
})
.build();
const result1 = await basicWorkflow.execute();
console.log(`\n✅ 基础错误处理结果: ${result1.success ? "成功" : "失败"}`);
console.log(`🎯 动态生成任务: ${result1.dynamicTasksGenerated || 0}个`);
console.log(`⏱️ 执行时间: ${result1.executionTime}ms`);
if (!result1.success) {
console.log(`❌ 主要错误: ${result1.error?.message}`);
}
// 示例2: 超时处理
console.log("\n🎯 示例2: 超时处理");
console.log("=".repeat(50));
const timeoutWorkflow = WorkflowBuilder.create()
.addTask(new SlowProcessingTask(6000)) // 6秒任务
.withConfig({
timeoutMs: 3000, // 3秒超时
})
.build();
const result2 = await timeoutWorkflow.execute();
console.log(
`\n⏰ 超时处理结果: ${result2.success ? "成功" : "失败(预期)"}`,
);
if (!result2.success) {
console.log(`❌ 超时错误: ${result2.error?.message}`);
}
// 示例3: 重试机制
console.log("\n🎯 示例3: 重试机制演示");
console.log("=".repeat(50));
const retryWorkflow = WorkflowBuilder.create()
.addTask(new RetryableTask(3))
.addTask(new HealthCheckTask())
.withConfig({
retryAttempts: 3,
})
.build();
const result3 = await retryWorkflow.execute();
console.log(`\n🔄 重试机制结果: ${result3.success ? "成功" : "失败"}`);
console.log(`⏱️ 执行时间: ${result3.executionTime}ms`);
// 示例4: 复合错误处理策略
console.log("\n🎯 示例4: 复合错误处理策略");
console.log("=".repeat(50));
const comprehensiveWorkflow = WorkflowBuilder.create()
.addTask(new NetworkRequestTask(0.7)) // 可能失败
.addTask(new DatabaseOperationTask(false))
.addTask(new SlowProcessingTask(1000))
// 多层错误处理策略
.addDynamicStrategy({
name: "immediate_fallback",
condition: (context) => {
// 检查是否有关键任务失败
const networkData = context.get("networkData");
return !networkData;
},
generator: async (context) => {
console.log("🚨 关键任务失败,立即启动备用流程");
return [new FallbackTask(), new HealthCheckTask()];
},
priority: 10,
})
.addDynamicStrategy({
name: "system_recovery",
condition: (context) => !!context.get("fallbackData"),
generator: async (context) => {
console.log("🔧 备用流程已启动,执行系统恢复");
return [new ErrorRecoveryTask()];
},
priority: 8,
})
.addDynamicStrategy({
name: "post_recovery_check",
condition: (context) => !!context.get("recoveryResult"),
generator: async (context) => {
console.log("📊 恢复完成,执行系统检查");
return [new HealthCheckTask(), new ErrorLoggingTask()];
},
priority: 5,
})
.withConfig({
retryAttempts: 2,
timeoutMs: 8000,
maxDynamicSteps: 10,
})
.build();
const result4 = await comprehensiveWorkflow.execute();
console.log(`\n🛡️ 综合错误处理结果: ${result4.success ? "成功" : "失败"}`);
console.log(`🎯 动态生成任务: ${result4.dynamicTasksGenerated || 0}个`);
console.log(`📈 总执行步数: ${result4.totalSteps || 0}`);
console.log(`🔧 最终任务总数: ${result4.taskResults.size}`);
console.log(`⏱️ 总执行时间: ${result4.executionTime}ms`);
// 详细结果分析
console.log("\n📊 详细执行分析:");
result4.taskResults.forEach((taskResult, taskName) => {
const status = taskResult.status === "completed" ? "✅" : "❌";
const type = taskName.includes("fallback")
? "🚨"
: taskName.includes("recovery")
? "🔧"
: taskName.includes("health")
? "📊"
: "⚙️";
console.log(
`${type} ${status} ${taskName}: ${taskResult.status} (${taskResult.duration}ms)`,
);
});
// 错误统计
const failedTasks = Array.from(result4.taskResults.values()).filter(
(r) => r.status === "failed",
);
const completedTasks = Array.from(result4.taskResults.values()).filter(
(r) => r.status === "completed",
);
console.log("\n📈 执行统计:");
console.log(`✅ 成功任务: ${completedTasks.length}个`);
console.log(`❌ 失败任务: ${failedTasks.length}个`);
console.log(
`📊 成功率: ${(
(completedTasks.length / result4.taskResults.size) * 100
).toFixed(1)}%`,
);
if (result4.success) {
console.log("\n🎉 系统展现出良好的容错能力和恢复机制!");
} else {
console.log("\n⚠️ 系统遇到了无法恢复的错误,但错误处理机制正常工作");
}
} catch (error) {
console.error("💥 错误处理示例执行异常:", error);
}
}
// 🚀 运行示例
if (import.meta.url === `file://${process.argv[1]}`) {
runErrorHandlingExample().catch(console.error);
}
export { runErrorHandlingExample };