fix: 回填命令异常时输出纯 ASCII 堆栈

py2 环境下 stderr 编码常是 ascii,Django 打印含中文的堆栈时会二次抛错,
只剩一行 UnicodeDecodeError,看不到真正出错的位置。
现在捕获异常后先把 traceback 转成 ASCII(非 ASCII 字符转义)输出,再抛 CommandError。

FFIB 4 小時之前
父節點
當前提交
03cd54d1c2
共有 1 個文件被更改,包括 24 次插入 和 0 次删除
  1. 24 0
      sales/management/commands/backfill_lottery_names.py

+ 24 - 0
sales/management/commands/backfill_lottery_names.py

@@ -152,6 +152,23 @@ def emit(stream, text):
152 152
         stream.write(text)
153 153
 
154 154
 
155
+def dump_ascii_traceback(stream):
156
+    """
157
+    把当前异常栈转成纯 ASCII 再输出。
158
+
159
+    py2 环境下 stderr 常见编码是 ascii,Django 打印含中文的堆栈时会二次抛错,
160
+    结果只剩一行 UnicodeDecodeError,看不到真正出错的位置。
161
+    """
162
+    import traceback
163
+
164
+    text = traceback.format_exc()
165
+
166
+    if not isinstance(text, type(u'')):
167
+        text = text.decode('utf-8', 'replace')
168
+
169
+    emit(stream, text.encode('ascii', 'backslashreplace').decode('ascii'))
170
+
171
+
155 172
 def setup_stdio_encoding():
156 173
     """服务器 locale 可能是 POSIX,stdout 编码为 ascii,输出中文会直接抛异常"""
157 174
     for stream in ('stdout', 'stderr'):
@@ -178,6 +195,13 @@ class Command(BaseCommand):
178 195
     def handle(self, *args, **options):
179 196
         setup_stdio_encoding()
180 197
 
198
+        try:
199
+            self.run_command(*args, **options)
200
+        except Exception:
201
+            dump_ascii_traceback(self.stderr)
202
+            raise CommandError('backfill failed, see ASCII traceback above')
203
+
204
+    def run_command(self, *args, **options):
181 205
         log_glob = options['log_glob']
182 206
 
183 207
         if options['parse_only']: