【问题标题】:python exception handlingpython异常处理
【发布时间】:2021-08-26 01:35:43
【问题描述】:

我正在开发一个 Django 站点,并且在尝试找出进行异常处理的最佳方法时遇到了麻烦。我一直在做

try:
    Some code
except:
    log error in my own words, i.e 'Some code' failed to execute
    Some other code

这会捕获所有异常,从而确保我的网站不会出现 500 错误等。但是,以我有限的知识,我正在丢失实际的异常,这使得调试变得非常痛苦。如何打印发生的错误?目前我注释掉 try: catch: 并查看错误并修复它。一定有更好的办法!

提前致谢

丰富

【问题讨论】:

  • 你在哪里见过这样的“赤裸裸的”except 声明?您能否提供显示此类编程的教程的报价或链接?这被认为是一种不好的做法。我想知道你从哪里学到的。
  • @S.Lott:与其贬低这样的人,不如提供一些替代方法并解释为什么它被认为是不好的做法。

标签: python


【解决方案1】:

您在异常变量中捕获异常:

try:
    # some code
except Exception, e:
    # Log the exception.

格式化异常有多种方法,日志模块(我假设你/Django 使用)支持格式化异常,异常本身通常在呈现为字符串时呈现有用的消息。

这是一个例子:

import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug('This message should go to the log file')

try:    
    1/0
except Exception as e:
    logging.exception(e)

此示例使用新的“as”语法来捕获异常,在 Python 2.6 及更高版本中受支持。上面的输出是:

DEBUG:root:This message should go to the log file
ERROR:root:integer division or modulo by zero
Traceback (most recent call last):
  File "untitled-1.py", line 6, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

【讨论】:

    【解决方案2】:
    #!/usr/bin/env python
    
    import sys
    
    try:
        0 / 0
    except Exception, e:
        print >> sys.stderr, 'Hello %s' % e
        # Hello integer division or modulo by zero
    

    请注意,您可以为一个块捕获多个异常,例如:

    try:
        open(filename)
    except NameError, e:
        print >> sys.stderr, e
    except IOError, ioe:
        print >> sys.stderr, ioe
    

    有关异常处理的更多信息可以在本教程中找到:

    【讨论】:

      【解决方案3】:

      这会有所帮助

      try:
      
          raise Exception('spam', 'eggs')
      
      except Exception as inst:
      
          print type(inst)     # the exception instance
          print inst.args      # arguments stored in .args
          print inst           # __str__ allows args to printed directly
          x, y = inst.args
          print 'x =', x
          print 'y =', y
      

      【讨论】:

        【解决方案4】:

        Django Middleware 是您在 Django 站点中处理异常的方式。

        要捕获所有异常,您必须创建一个 Django 中间件并创建一个 process_exception 方法。

        from django.http import HttpResponse
        
        class SomeMiddleware(object):
            def process_exception(self, request, exception):
                'Intercept exceptions'
        
                return HttpResponse('Hey! an error occurred',
                        content_type='text/plain')
        

        然后将其添加到 MIDDLEWARE_CLASSES 设置中:

        MIDDLEWARE_CLASSES = (
            # ...
            'some.module.SomeMiddleware',
        )
        

        然后您可以控制遇到任何异常时的处理方式。

        我认为这回答了您的问题。但你可能会更好overriding the 500.html template or the handler500 view。请注意,只有在项目设置中将 DEBUG 设置为 False 后,这些视图才会发挥作用。

        【讨论】:

          【解决方案5】:

          试试这个:

          try:
            # some code
          except Exception, e:
            # log error with data from e
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2022-10-14
            • 1970-01-01
            • 2011-10-09
            • 2017-04-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多