处理Python包中未处理的异常

时间:2014-09-14 23:29:25

标签: python django wordpress

我已成功通过the-real-django-wordpress Python包(Github)将我的Wordpress博客整合到我的Django应用程序中。

我唯一需要做的就是:

  • 将Wordpress数据库凭据添加到Django设置
  • 将包的URLconf包含在urls.py
  • override the package templates以便按照我想要的方式显示帖子。

如果Wordpress数据库碰巧离线,我会得到一个Python例外。

  

操作错误:(2003年,"无法连接到MySQL服务器' 10.0.2.2'   (110)&#34)

Python代码是包的一部分,因此不在我的代码中,我应该在哪里处理异常以显示错误消息?

1 个答案:

答案 0 :(得分:2)

为什么不让您的500.html模板只显示您想要的错误消息?

否则,您可以创建一个中间件来捕获此错误:

from django.shortcuts import render

class CatchOperationalError(object):
    def process_exception(self, request, exception):
        if type(exception).__name__ == 'OperationalError':  # replace with proper isinstance
            return render(request, 'wordpress_down.html')

https://docs.djangoproject.com/en/dev/topics/http/middleware/#process_exception

另一种选择是将每个单独的视图包装在try / except中。