Python 捕获异常并将其输出到django';s信息系统

Python 捕获异常并将其输出到django';s信息系统,python,django,exception-handling,Python,Django,Exception Handling,所以我注意到Django有一个很好的消息框架。它有5个不同的级别(信息、错误、调试、警告和成功) 将异常一直传播到视图级别,并报告其中一些异常,这将非常好 利比 def read_file(user, filename, **kwargs): try: with open(...): return f.read() except Exception, e: raise e utli.py def wrapper_read_file(user, f

所以我注意到Django有一个很好的消息框架。它有5个不同的级别(信息、错误、调试、警告和成功)

将异常一直传播到视图级别,并报告其中一些异常,这将非常好

利比

def read_file(user, filename, **kwargs):
   try:
     with open(...):
        return f.read()
   except Exception, e:
     raise e
utli.py

def wrapper_read_file(user, filename, **kwargs):
   try:
      if user.is_authenticated and user.belongs('admin'):
          lib.read_file(...)
      else:
          raise Exception("Unauthenticated user!!!")
   except Exception, e:
      raise e
views.py

def my_view(request):
   [..] do something here
   try:
     result = wrapper_read_file(...)
     return render(request, 'hello.html', {'result': result})
   except Exception, e:
     if isinstance(e, IOError):
         if e.errno==errno.ENOENT:
         messages.add_message(request, message.ERROR, 'File does not exist.')
     elif isinstance(e, OSError):
         messages.add_message(request, message.ERROR, 'You don't have sufficient permission to open the file.')
     return render(request, 'hello.html', {'hello_world': 'hello_world'}
Django知道如何呈现
消息
,我有能力做到这一点。因此,它将显示
消息


你认为我的异常处理看起来合理吗?有其他建议吗?我对Python错误异常处理相当陌生。

您可能不想捕获每个异常。这可能会掩盖其他错误,并会阻止Ctrl-C工作。相反,只捕获要处理的异常

try:
    # action that may throw an exception
except IOError, e: # Will only catch IOErrors
    if e.errno == errno.ENOENT:
        messages.add_message(request, messages.ERROR, "File not found")
    else:
        raise e    # Re-raise other IOErrors
except OSError, e: # Will only catch OSErrors
    messages.add_message(request, messages.ERROR, "Insufficient permissions")

return render(request, 'hello.html', {})

更新:添加第二个except子句以处理其他异常类型。请注意,这可能还不够,因为这使得(大)假设所有的
操作系统错误都与权限相关。

Schinkckel谢谢。很抱歉反应太晚。在您的代码片段中,您是否建议我只捕获调用方级别的特定异常,而让被调用方的其余部分只引发异常?
异常作为e
是一个很好的异常捕获吗?假设A调用B,B调用C,C调用D,在什么条件下,除了在A(像代码片段一样,A可以是我们的视图函数)之外,我还希望捕获级别B,C的特定异常。?最后,如果在
else
子句中失败,我的原始代码如何掩盖其他错误?在your views.py中,捕获每个异常,然后在最终呈现之前针对某些异常类型进行测试。您没有针对所有可能的异常类型进行测试,因此可能会生成另一个异常,然后呈现页面,就好像没有异常一样。这也绕过了任何中间件异常处理(这确实是一种更好的方法)。