-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_handling.py
More file actions
559 lines (472 loc) · 19 KB
/
error_handling.py
File metadata and controls
559 lines (472 loc) · 19 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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
#!/usr/bin/env python3
"""
Scintirete SDK 错误处理示例
演示如何正确处理使用 Scintirete Python SDK 时可能遇到的各种错误情况。
"""
import time
import asyncio
from typing import List
from scintirete_sdk import (
ScintireteClient,
ScintireteAsyncClient,
DistanceMetric,
HnswConfig,
Vector,
ScintireteError,
ConnectionError,
AuthenticationError,
DatabaseError,
CollectionError,
VectorError,
)
def demonstrate_connection_errors():
"""演示连接错误处理"""
print("\n🔌 连接错误处理演示")
print("=" * 50)
# 1. 连接到不存在的服务器
print("1. 尝试连接不存在的服务器...")
try:
client = ScintireteClient("non-existent-server:50051", default_timeout=5.0)
client.list_databases()
client.close()
except ConnectionError as e:
print(f" ✅ 捕获到连接错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 2. 连接超时
print("\n2. 连接超时测试...")
try:
# 使用非常短的超时时间
client = ScintireteClient("localhost:50051", default_timeout=0.001)
client.list_databases()
client.close()
except ConnectionError as e:
print(f" ✅ 捕获到超时错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 3. TLS 连接错误(如果服务器不支持TLS)
print("\n3. TLS 连接错误测试...")
try:
client = ScintireteClient("localhost:50051", use_tls=True, default_timeout=5.0)
client.list_databases()
client.close()
except ConnectionError as e:
print(f" ✅ 捕获到TLS连接错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
def demonstrate_authentication_errors():
"""演示认证错误处理"""
print("\n🔐 认证错误处理演示")
print("=" * 50)
# 1. 错误的密码
print("1. 使用错误密码连接...")
try:
with ScintireteClient("localhost:50051", password="wrong_password") as client:
client.list_databases()
except AuthenticationError as e:
print(f" ✅ 捕获到认证错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 2. 缺少必需的认证信息
print("\n2. 缺少认证信息测试...")
try:
# 如果服务器需要认证但未提供密码
with ScintireteClient("localhost:50051") as client:
# 尝试执行需要认证的操作
client.create_database("test_auth_db")
except AuthenticationError as e:
print(f" ✅ 捕获到认证错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
def demonstrate_database_errors(client: ScintireteClient):
"""演示数据库操作错误处理"""
print("\n💾 数据库错误处理演示")
print("=" * 50)
# 1. 创建已存在的数据库
print("1. 重复创建数据库...")
db_name = "test_error_db"
try:
# 先创建数据库
client.create_database(db_name)
print(f" 创建数据库 {db_name} 成功")
# 再次创建相同的数据库
client.create_database(db_name)
print(f" 重复创建数据库 {db_name} 成功")
except DatabaseError as e:
print(f" ✅ 捕获到数据库错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 2. 删除不存在的数据库
print("\n2. 删除不存在的数据库...")
try:
client.drop_database("non_existent_database")
except DatabaseError as e:
print(f" ✅ 捕获到数据库错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 3. 访问不存在的数据库
print("\n3. 访问不存在的数据库...")
try:
client.list_collections("non_existent_database")
except DatabaseError as e:
print(f" ✅ 捕获到数据库错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
return db_name
def demonstrate_collection_errors(client: ScintireteClient, db_name: str):
"""演示集合操作错误处理"""
print("\n📁 集合错误处理演示")
print("=" * 50)
collection_name = "test_error_collection"
# 1. 在不存在的数据库中创建集合
print("1. 在不存在的数据库中创建集合...")
try:
client.create_collection(
db_name="non_existent_db",
collection_name=collection_name,
metric_type=DistanceMetric.COSINE
)
except DatabaseError as e:
print(f" ✅ 捕获到数据库错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 2. 创建已存在的集合
print("\n2. 重复创建集合...")
try:
# 先创建集合
client.create_collection(
db_name=db_name,
collection_name=collection_name,
metric_type=DistanceMetric.COSINE
)
print(f" 创建集合 {collection_name} 成功")
# 再次创建相同的集合
client.create_collection(
db_name=db_name,
collection_name=collection_name,
metric_type=DistanceMetric.L2
)
except CollectionError as e:
print(f" ✅ 捕获到集合错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 3. 访问不存在的集合
print("\n3. 访问不存在的集合...")
try:
client.get_collection_info(db_name, "non_existent_collection")
except CollectionError as e:
print(f" ✅ 捕获到集合错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 4. 删除不存在的集合
print("\n4. 删除不存在的集合...")
try:
client.drop_collection(db_name, "non_existent_collection")
except CollectionError as e:
print(f" ✅ 捕获到集合错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
return collection_name
def demonstrate_vector_errors(client: ScintireteClient, db_name: str, collection_name: str):
"""演示向量操作错误处理"""
print("\n🎯 向量错误处理演示")
print("=" * 50)
# 1. 插入维度不匹配的向量
print("1. 插入维度不匹配的向量...")
try:
# 先插入一个正常的向量来确定集合维度
normal_vector = Vector(elements=[0.1, 0.2, 0.3, 0.4])
client.insert_vectors(db_name, collection_name, [normal_vector])
print(" 插入正常向量成功")
# 插入维度不匹配的向量
wrong_dim_vector = Vector(elements=[0.1, 0.2]) # 维度不匹配
client.insert_vectors(db_name, collection_name, [wrong_dim_vector])
except VectorError as e:
print(f" ✅ 捕获到向量错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 2. 插入空向量
print("\n2. 插入空向量...")
try:
empty_vector = Vector(elements=[])
client.insert_vectors(db_name, collection_name, [empty_vector])
except VectorError as e:
print(f" ✅ 捕获到向量错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 3. 搜索维度不匹配的向量
print("\n3. 搜索维度不匹配的向量...")
try:
client.search(
db_name=db_name,
collection_name=collection_name,
query_vector=[0.1, 0.2], # 维度不匹配
top_k=5
)
except VectorError as e:
print(f" ✅ 捕获到向量错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 4. 删除不存在的向量ID
print("\n4. 删除不存在的向量ID...")
try:
# 使用非常大的ID,应该不存在
non_existent_ids = [999999, 999998, 999997]
deleted_count = client.delete_vectors(db_name, collection_name, non_existent_ids)
print(f" 删除了 {deleted_count} 个向量(预期为0)")
except VectorError as e:
print(f" ✅ 捕获到向量错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 5. 在空集合中搜索
print("\n5. 在空集合中搜索...")
try:
# 创建一个新的空集合
empty_collection = "empty_collection"
client.create_collection(
db_name=db_name,
collection_name=empty_collection,
metric_type=DistanceMetric.COSINE
)
results = client.search(
db_name=db_name,
collection_name=empty_collection,
query_vector=[0.1, 0.2, 0.3, 0.4],
top_k=5
)
print(f" 在空集合中搜索,结果数: {len(results)}")
except VectorError as e:
print(f" ✅ 捕获到向量错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
def demonstrate_parameter_validation_errors(client: ScintireteClient, db_name: str, collection_name: str):
"""演示参数验证错误处理"""
print("\n🔍 参数验证错误处理演示")
print("=" * 50)
# 1. 无效的 top_k 值
print("1. 无效的 top_k 值...")
try:
client.search(
db_name=db_name,
collection_name=collection_name,
query_vector=[0.1, 0.2, 0.3, 0.4],
top_k=0 # 无效值
)
except VectorError as e:
print(f" ✅ 捕获到参数错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 2. 负数的 top_k 值
print("\n2. 负数的 top_k 值...")
try:
client.search(
db_name=db_name,
collection_name=collection_name,
query_vector=[0.1, 0.2, 0.3, 0.4],
top_k=-5 # 负数
)
except VectorError as e:
print(f" ✅ 捕获到参数错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 3. 空的数据库名称
print("\n3. 空的数据库名称...")
try:
client.create_database("") # 空名称
except DatabaseError as e:
print(f" ✅ 捕获到参数错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
# 4. 空的集合名称
print("\n4. 空的集合名称...")
try:
client.create_collection(
db_name=db_name,
collection_name="", # 空名称
metric_type=DistanceMetric.COSINE
)
except CollectionError as e:
print(f" ✅ 捕获到参数错误: {e}")
except Exception as e:
print(f" ⚠️ 其他错误: {e}")
def demonstrate_retry_and_recovery():
"""演示重试和恢复机制"""
print("\n🔄 重试和恢复机制演示")
print("=" * 50)
def robust_operation_with_retry(operation_func, max_retries: int = 3, delay: float = 1.0):
"""带重试的操作包装器"""
for attempt in range(max_retries):
try:
return operation_func()
except ConnectionError as e:
if attempt < max_retries - 1:
print(f" 尝试 {attempt + 1} 失败: {e}")
print(f" 等待 {delay} 秒后重试...")
time.sleep(delay)
delay *= 2 # 指数退避
else:
print(f" 所有 {max_retries} 次尝试都失败了")
raise
except Exception as e:
print(f" 遇到不可重试的错误: {e}")
raise
# 模拟不稳定的连接
print("1. 模拟连接重试...")
def unstable_connection():
# 这里可以模拟偶尔失败的连接
client = ScintireteClient("localhost:50051", default_timeout=5.0)
try:
return client.list_databases()
finally:
client.close()
try:
databases = robust_operation_with_retry(unstable_connection)
print(f" ✅ 重试成功,获取到数据库: {databases}")
except Exception as e:
print(f" ❌ 重试失败: {e}")
async def demonstrate_async_error_handling():
"""演示异步错误处理"""
print("\n🚀 异步错误处理演示")
print("=" * 50)
# 1. 异步连接错误
print("1. 异步连接错误...")
try:
async with ScintireteAsyncClient("non-existent:50051", default_timeout=2.0) as client:
await client.list_databases()
except ConnectionError as e:
print(f" ✅ 捕获到异步连接错误: {e}")
except Exception as e:
print(f" ⚠️ 其他异步错误: {e}")
# 2. 异步操作超时
print("\n2. 异步操作超时...")
try:
async with ScintireteAsyncClient("localhost:50051", default_timeout=0.001) as client:
await client.create_database("timeout_test")
except ConnectionError as e:
print(f" ✅ 捕获到异步超时错误: {e}")
except Exception as e:
print(f" ⚠️ 其他异步错误: {e}")
# 3. 异步并发错误处理
print("\n3. 异步并发错误处理...")
async def failing_operation(operation_id: int):
"""模拟可能失败的异步操作"""
if operation_id % 3 == 0: # 每3个操作失败一次
raise VectorError(f"模拟操作 {operation_id} 失败")
return f"操作 {operation_id} 成功"
tasks = [failing_operation(i) for i in range(10)]
results = await asyncio.gather(*tasks, return_exceptions=True)
successful = sum(1 for r in results if not isinstance(r, Exception))
failed = sum(1 for r in results if isinstance(r, Exception))
print(f" 并发操作结果: {successful} 成功, {failed} 失败")
for i, result in enumerate(results):
if isinstance(result, Exception):
print(f" 操作 {i}: ❌ {result}")
else:
print(f" 操作 {i}: ✅ {result}")
def demonstrate_graceful_degradation(client: ScintireteClient):
"""演示优雅降级"""
print("\n🛡️ 优雅降级演示")
print("=" * 50)
def search_with_fallback(db_name: str, collection_name: str, query_vector: List[float], top_k: int = 10):
"""带降级策略的搜索"""
fallback_strategies = [
{"top_k": top_k, "include_vector": True, "description": "完整搜索"},
{"top_k": min(top_k, 50), "include_vector": False, "description": "降低top_k,不返回向量"},
{"top_k": min(top_k, 10), "include_vector": False, "description": "进一步降低top_k"},
]
for i, strategy in enumerate(fallback_strategies):
try:
print(f" 尝试策略 {i+1}: {strategy['description']}")
results = client.search(
db_name=db_name,
collection_name=collection_name,
query_vector=query_vector,
top_k=strategy["top_k"],
include_vector=strategy["include_vector"]
)
print(f" ✅ 策略 {i+1} 成功,返回 {len(results)} 个结果")
return results
except Exception as e:
print(f" ❌ 策略 {i+1} 失败: {e}")
if i < len(fallback_strategies) - 1:
print(f" 尝试下一个策略...")
else:
print(f" 所有策略都失败,返回空结果")
return []
# 创建测试环境
try:
db_name = "graceful_test_db"
collection_name = "graceful_test_collection"
# 清理并创建
try:
client.drop_database(db_name)
except:
pass
client.create_database(db_name)
client.create_collection(
db_name=db_name,
collection_name=collection_name,
metric_type=DistanceMetric.COSINE
)
# 插入一些测试数据
vectors = [Vector(elements=[0.1, 0.2, 0.3, 0.4]) for _ in range(5)]
client.insert_vectors(db_name, collection_name, vectors)
# 测试优雅降级
query_vector = [0.1, 0.2, 0.3, 0.4]
results = search_with_fallback(db_name, collection_name, query_vector, top_k=100)
# 清理
client.drop_database(db_name)
except Exception as e:
print(f" 优雅降级测试失败: {e}")
async def main():
"""主函数"""
SERVER_ADDRESS = "localhost:50051"
PASSWORD = None # 根据实际情况设置
print("🚨 Scintirete SDK 错误处理演示")
print("=" * 60)
try:
# 基本连接错误演示(不需要真实服务器)
demonstrate_connection_errors()
demonstrate_authentication_errors()
# 异步错误处理演示
await demonstrate_async_error_handling()
# 重试机制演示
demonstrate_retry_and_recovery()
# 以下演示需要真实的服务器连接
print(f"\n📡 尝试连接到真实服务器: {SERVER_ADDRESS}")
try:
with ScintireteClient(SERVER_ADDRESS, password=PASSWORD, default_timeout=5.0) as client:
print("✅ 服务器连接成功,开始详细错误演示...")
# 数据库错误演示
db_name = demonstrate_database_errors(client)
# 集合错误演示
collection_name = demonstrate_collection_errors(client, db_name)
# 向量错误演示
demonstrate_vector_errors(client, db_name, collection_name)
# 参数验证错误演示
demonstrate_parameter_validation_errors(client, db_name, collection_name)
# 优雅降级演示
demonstrate_graceful_degradation(client)
# 清理测试数据
try:
client.drop_database(db_name)
print(f"\n🧹 清理测试数据库: {db_name}")
except:
pass
except ConnectionError as e:
print(f"❌ 无法连接到服务器: {e}")
print("💡 请确保 Scintirete 服务器正在运行")
print("\n🎉 错误处理演示完成!")
print("\n📝 错误处理最佳实践总结:")
print(" 1. 始终使用 try-except 捕获特定的异常类型")
print(" 2. 实现重试机制处理临时性错误")
print(" 3. 使用上下文管理器确保资源正确释放")
print(" 4. 实现优雅降级策略")
print(" 5. 记录详细的错误信息用于调试")
print(" 6. 区分可重试错误和永久性错误")
except Exception as e:
print(f"❌ 演示过程中发生未预期错误: {e}")
raise
if __name__ == "__main__":
# 运行演示
asyncio.run(main())