【问题标题】:Python 2.7: Save all exceptions into database (convert to unicode Problems)Python 2.7:将所有异常保存到数据库中(转换为 unicode 问题)
【发布时间】:2018-07-12 21:41:30
【问题描述】:

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

我的问题是有些错误消息我无法转换为 unicode(尤其是一些 WindowsErrors 和带有德语“元音变音”的错误:ä、ö、ü)。因为我事先不知道所有可能的错误我想要一个可以处理所有错误并将它们的消息转换为 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)

注意:我发现有些异常有一个名为.msg.str的属性,但不是全部!

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

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

谢谢!

塞巴斯蒂安

【问题讨论】:

    标签: database python-2.7 unicode sqlite exception-handling


    【解决方案1】:

    如果如您的演示所示,源文件已知为 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: ä!
    

    【讨论】:

    • 非常感谢!为我工作!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 2012-12-23
    • 2015-09-14
    • 2018-08-29
    • 2018-09-28
    • 1970-01-01
    相关资源
    最近更新 更多