瀏覽代碼

refactor(core): 重构异常处理以使用统一处理器并改进代码组织

将基于列表的异常处理器替换为基于字典的 EXCEPTION_MAPPINGS,以提高可维护性
将多个处理函数合并为单个 unified_exception_handler,以实现一致的错误响应
删除异常类定义之间不必要的空行
添加全面的文档字符串,解释异常注册和统一处理器的行为
简化异常处理器注册循环,直接遍历映射的异常类
通过更清晰的变量命名改进类型提示和代码可读性
chensiyu 1 月之前
父節點
當前提交
f961dd20df
共有 1 個文件被更改,包括 25 次插入22 次删除
  1. 25 22
      app/core/exceptions.py

+ 25 - 22
app/core/exceptions.py

@@ -1,42 +1,45 @@
1 1
 from fastapi import FastAPI, Request
2 2
 from fastapi.responses import JSONResponse
3 3
 
4
-
5 4
 class DocumentNotFoundError(Exception):
6 5
     def __init__(self, document_id: str):
7 6
         super().__init__(f"Document '{document_id}' not found")
8 7
 
9
-
10 8
 class DocumentParseError(Exception):
11 9
     """Word 下载或解析失败。"""
12 10
     pass
13 11
 
14
-
15 12
 class ExportError(Exception):
16 13
     pass
17 14
 
18
-
19 15
 class RecordNotFoundError(Exception):
20 16
     def __init__(self, record_id: str):
21 17
         super().__init__(f"Export record '{record_id}' not found")
22 18
 
23
-
24
-_HANDLERS: list[tuple[type[Exception], int, int]] = [
25
-    (DocumentNotFoundError, 404, 404),
26
-    (DocumentParseError,    400, 400),
27
-    (ExportError,           500, 500),
28
-    (RecordNotFoundError,   404, 4041),
29
-]
30
-
19
+# 异常映射配置:异常类 -> (HTTP状态码, 业务错误码)
20
+EXCEPTION_MAPPINGS: dict[type[Exception], tuple[int, int]] = {
21
+    DocumentNotFoundError: (404, 404),
22
+    DocumentParseError: (400, 400),
23
+    ExportError: (500, 500),
24
+    RecordNotFoundError: (404, 4041),
25
+}
31 26
 
32 27
 def register_exception_handlers(app: FastAPI) -> None:
33
-    def _make_handler(http_status: int, code: int):
34
-        async def handler(request: Request, exc: Exception) -> JSONResponse:
35
-            return JSONResponse(
36
-                status_code=http_status,
37
-                content={"code": code, "message": str(exc), "data": None},
38
-            )
39
-        return handler
40
-
41
-    for exc_class, http_status, code in _HANDLERS:
42
-        app.add_exception_handler(exc_class, _make_handler(http_status, code))
28
+    """注册全局异常处理器,所有自定义异常返回标准格式:{"code": int, "message": str, "data": None}"""
29
+    async def unified_exception_handler(request: Request, exc: Exception) -> JSONResponse:
30
+        """统一异常处理函数"""
31
+        # 从映射中获取配置,如果不存在则使用默认值 (500, 500)
32
+        http_status, error_code = EXCEPTION_MAPPINGS.get(type(exc), (500, 500))
33
+        
34
+        return JSONResponse(
35
+            status_code=http_status,
36
+            content={
37
+                "code": error_code,
38
+                "message": str(exc),
39
+                "data": None,
40
+            },
41
+        )
42
+    
43
+    # 为所有配置的异常类型注册同一个处理函数
44
+    for exc_class in EXCEPTION_MAPPINGS:
45
+        app.add_exception_handler(exc_class, unified_exception_handler)