-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror_handler.py
More file actions
271 lines (219 loc) · 9.41 KB
/
Copy patherror_handler.py
File metadata and controls
271 lines (219 loc) · 9.41 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
"""全局异常捕获
在 PyInstaller --windowed 模式下控制台不可见,未处理异常会导致程序静默退出。
Flet 内部将同步事件处理器(on_click 等)通过 ThreadPoolExecutor 执行,
异常被 Future 吞掉,sys.excepthook 无法捕获。本模块通过以下机制解决:
1. Monkey-patch Page.__context_wrapper — 拦截所有事件处理器异常(主路径)
2. sys.excepthook — 兜底,处理 Flet 事件循环之外的异常(如后台线程)
异常发生时会:
- 将完整 Traceback 写入 config/logs/error_YYYYMMDD_HHMMSS.log
- 在 Flet 页面上弹窗提示用户
"""
import functools
import sys
import traceback
from datetime import datetime
from pathlib import Path
import flet as ft
from config import LOG_DIR
from constants import (
BTN_CONFIRM, COLOR_DANGER, COLOR_ERROR_BG,
FONT_SIZE_SMALL, FONT_SIZE_BODY, MAX_LOG_FILES,
)
# ---------- 日志目录 ----------
# LOG_DIR 已从 config 导入,此处保留兼容
# 保存 page 引用
_page_ref: ft.Page | None = None
_original_excepthook = None
def setup_error_handler(page: ft.Page) -> None:
"""注册全局异常钩子。应在 main(page) 中尽早调用。"""
global _page_ref, _original_excepthook
_page_ref = page
# 主路径:拦截 Flet 内部事件处理器中的异常
_patch_flet_handler(page)
# 兜底:Flet 事件循环之外的异常(如后台线程)
if _original_excepthook is None:
_original_excepthook = sys.excepthook
sys.excepthook = _exception_hook
# ---------------------------------------------------------------------------
# Monkey-patch Flet 内部事件分发
# ---------------------------------------------------------------------------
def _patch_flet_handler(page: ft.Page) -> None:
"""替换 Page.__context_wrapper,在用户回调外层包裹异常捕获。
Flet 的 run_thread 通过 __context_wrapper → ThreadPoolExecutor 执行同步
事件处理器,异常被 Future 吞掉。这里在 wrapper 层加上 try/except 解决。
若未来 Flet 版本变更导致属性名不兼容,静默降级(至少 sys.excepthook 仍在)。
"""
try:
# Python name mangling: __context_wrapper → _Page__context_wrapper
_original_wrapper = page._Page__context_wrapper # noqa: SLF001
except AttributeError:
return
def _patched_wrapper(handler):
wrapped = _original_wrapper(handler)
@functools.wraps(wrapped)
def safe_wrapper(*args):
try:
wrapped(*args)
except Exception:
_handle_flet_exception(*sys.exc_info())
return safe_wrapper
page._Page__context_wrapper = _patched_wrapper # noqa: SLF001
# ---------------------------------------------------------------------------
# 统一的异常处理入口
# ---------------------------------------------------------------------------
def _handle_flet_exception(exc_type, exc_value, exc_tb) -> None:
"""处理来自 Flet 事件循环的异常。"""
# 1. 写入日志
log_path = _write_exception_log(exc_type, exc_value, exc_tb)
# 2. 弹窗
_show_error_dialog(exc_type, exc_value, log_path)
# ---------------------------------------------------------------------------
# sys.excepthook 兜底
# ---------------------------------------------------------------------------
def _exception_hook(exc_type, exc_value, exc_tb):
"""sys.excepthook 回调 — Flet 事件循环之外的异常。"""
log_path = _write_exception_log(exc_type, exc_value, exc_tb)
_show_error_dialog(exc_type, exc_value, log_path)
if _original_excepthook is not None:
_original_excepthook(exc_type, exc_value, exc_tb)
# ---------------------------------------------------------------------------
# 日志写入
# ---------------------------------------------------------------------------
def _write_exception_log(exc_type, exc_value, exc_tb) -> Path | None:
"""将异常 Traceback 写入带时间戳的日志文件,同时写入主日志。"""
try:
LOG_DIR.mkdir(parents=True, exist_ok=True)
now = datetime.now()
timestamp = now.strftime("%Y%m%d_%H%M%S")
filename = f"error_{timestamp}.log"
log_path = LOG_DIR / filename
tb_lines = traceback.format_exception(exc_type, exc_value, exc_tb)
full_tb = "".join(tb_lines)
content = (
f"错误发生时间:{now.strftime('%Y-%m-%d %H:%M:%S')}\n"
f"══════════════════════════════════════════════\n\n"
f"{full_tb}\n"
f"══════════════════════════════════════════════\n"
)
log_path.write_text(content, encoding="utf-8")
# 同时写入主日志
try:
import logging
err_logger = logging.getLogger("ERROR")
err_logger.error(
f"未捕获异常: {exc_type.__name__} - {exc_value}\n{full_tb.strip()}"
)
except Exception:
pass
_cleanup_old_logs()
return log_path
except Exception:
return None
def _cleanup_old_logs() -> None:
"""删除超出数量限制的旧错误日志和应用日志。"""
try:
# 清理旧的独立错误日志文件
error_logs = sorted(LOG_DIR.glob("error_*.log"), key=lambda p: p.stat().st_mtime)
while len(error_logs) > MAX_LOG_FILES:
oldest = error_logs.pop(0)
oldest.unlink(missing_ok=True)
# 清理旧的按天应用日志(app_*.log 和 app.log.2026-08-03 格式)
app_logs = sorted(
[p for p in LOG_DIR.glob("app*") if p.suffix in (".log", "") or ".log." in p.name],
key=lambda p: p.stat().st_mtime,
)
while len(app_logs) > MAX_LOG_FILES:
oldest = app_logs.pop(0)
oldest.unlink(missing_ok=True)
except Exception:
pass
# ---------------------------------------------------------------------------
# 错误弹窗
# ---------------------------------------------------------------------------
def _show_error_dialog(exc_type, exc_value, log_path: Path | None) -> None:
"""在 Flet 页面上弹出错误提示对话框。
整个函数用 try/except 包裹——错误处理本身绝不应再抛异常。
"""
page = _page_ref
if page is None:
return
try:
error_type = exc_type.__name__ if exc_type else "UnknownError"
error_message = str(exc_value) if exc_value else "(无详细描述)"
# 完整 Traceback 文本
tb_text = "".join(
traceback.format_exception(exc_type, exc_value, exc_value.__traceback__)
)
# 弹窗中的显示内容:截取前 30 行
tb_lines = tb_text.strip().split("\n")
truncated = len(tb_lines) > 30
if truncated:
tb_lines = tb_lines[:30]
tb_lines.append("... (完整信息已写入日志文件)")
tb_display = "\n".join(tb_lines)
log_info = f"\n\n📄 日志文件已保存至:\n{log_path}" if log_path else ""
dialog = ft.AlertDialog(
modal=True,
title=ft.Row(
[
ft.Icon(ft.Icons.ERROR_OUTLINE, color=COLOR_DANGER, size=24),
ft.Text(
"程序错误", size=FONT_SIZE_BODY,
weight=ft.FontWeight.BOLD, color=COLOR_DANGER,
),
],
spacing=8,
),
content=ft.Column(
[
ft.Container(
ft.Text(
f"❌ {error_type}:{error_message}{log_info}",
size=FONT_SIZE_SMALL,
selectable=True,
),
bgcolor=COLOR_ERROR_BG,
border_radius=8,
padding=12,
),
ft.Container(
content=ft.Column(
[
ft.Text(
tb_display,
size=11,
selectable=True,
color="#555555",
),
],
scroll=ft.ScrollMode.AUTO,
height=240,
),
bgcolor="#fafafa",
border=ft.border.all(1, "#e0e0e0"),
border_radius=8,
padding=12,
margin=ft.margin.only(top=8, bottom=0, left=0, right=0),
),
],
scroll=ft.ScrollMode.AUTO,
width=600,
height=400,
),
actions=[
ft.TextButton(
BTN_CONFIRM,
on_click=lambda e: _close_dialog(e.page, dialog),
),
],
actions_alignment=ft.MainAxisAlignment.END,
)
page.open(dialog)
except Exception:
pass
def _close_dialog(page: ft.Page, dialog: ft.AlertDialog) -> None:
"""关闭错误对话框。"""
try:
page.close(dialog)
except Exception:
pass