Python 2.7:将所有异常保存到数据库中(转换为unicode问题)

Python 2.7: Save all exceptions into database (convert to unicode Problems)

我正在尝试将 python 服务(运行 隐藏在 Windows 7/10)抛出的所有异常保存到 sqlite3 数据库文件中。除了其他东西(回溯、日期等)之外,我还想保存错误消息。

我的问题是有些错误消息我无法转换为 unicode(尤其是一些 Windows 错误和德语错误 'Umlaut':ä、ö、ü)。因为我事先不知道每个可能的错误我想要一个可以处理所有错误并将它们的消息转换为 unicode 的函数

谁能告诉我 convertToUnicode 函数应该是什么样子的?

# -*- coding: utf-8 -*-

def someErrorneousFunction():
    raise RuntimeError('Not a unicode string. But with a german Umlaut: ä!')

def saveExceptionToDBThatOnlyAcceptsUnicode(msg):
    """SQL INSERT SOME STUFF... + THE UNICODE ERROR MESSAGE!"""
    pass

def convertToUnicode(e):
    """ What to do here ??? """
    pass

try:
    someErrorneousFunction()
except Exception as e:
    unicode_error_msg = convertToUnicode(e)
    saveExceptionToDBThatOnlyAcceptsUnicode(unicode_error_msg)

注意:我发现有些Exception有一个叫做.msg.str[=33=的属性],但不是全部!

这种方法是否有意义?我知道不加区分地捕获所有异常是一种不好的做法,但由于我的软件偶尔会在其他地方处于测试模式,而且我想获取每封邮件的异常数据库,这对我来说似乎很有意义。此外,我将我知道的错误与我事先不知道的错误区分开来。

如有任何建议,我将不胜感激!

谢谢!

塞巴斯蒂安

如果如您的演示所示,源文件已知为 UTF-8,那么这应该有效:

# -*- coding: utf-8 -*-
import traceback

def someErrorneousFunction():
    raise RuntimeError('Not a unicode string. But with a german Umlaut: ä!')

def saveExceptionToDBThatOnlyAcceptsUnicode(msg):
    print type(msg)
    print msg

def convertToUnicode(e):
    return traceback.format_exc(e).decode('utf8')

try:
    someErrorneousFunction()
except Exception as e:
    unicode_error_msg = convertToUnicode(e)
    saveExceptionToDBThatOnlyAcceptsUnicode(unicode_error_msg)

输出:

<type 'unicode'>
Traceback (most recent call last):
  File "C:\test.py", line 15, in <module>
    someErrorneousFunction()
  File "C:\test.py", line 5, in someErrorneousFunction
    raise RuntimeError('Not a unicode string. But with a german Umlaut: ä!')
RuntimeError: Not a unicode string. But with a german Umlaut: ä!