Django:如何使用断言...而不显示系统错误页面?
我是 Django 新手,在 view.py 中有一些代码,如下所示:
try:
myfunction()
except:
assert False, sys.exc_info()[0]
这非常有帮助,因为如果出现错误,我会收到一封包含大量有用信息的电子邮件。 问题是它还将用户重定向到 Webfaction 系统错误页面。我想知道的是如何仍然获得有用的错误电子邮件,但将用户重定向到我自己的错误页面?
另外,这是在 Django 中处理错误的最佳方法吗?
I'm new to Django and have some code in my views.py like this:
try:
myfunction()
except:
assert False, sys.exc_info()[0]
This is very helpful because I get an email with lots of useful info if there's an error.
The problem is that it also redirects the user to a Webfaction system error page. What I'd like to know is how do I still get the useful error email, but redirect the user to my own error page?
Also, is this the best way to be handling errors in Django?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这在很多层面上都是错误的。
首先,没有理由捕获一个异常只是为了引发另一个异常。如果您的应用程序引发异常,那么 Django 自己的中间件将捕获它,并根据您是否有
DEBUG=True
,显示详细的调试页面,或将异常邮寄给中提到的用户ADMINS
设置。其次,您永远不应该收到 Webfaction 错误页面 - 我什至无法想象这是如何发生的。如果您希望用户看到一个漂亮的错误页面,您应该定义 404.html 和 500.html 模板,如果您的需求更复杂,甚至可以定义完整的错误处理视图。 文档中对此进行了充分解释 。
This is wrong on quite a few levels.
Firstly, there is no reason to catch an exception only to raise another one. If your application raises an exception, then Django's own middleware will catch it, and depending on whether or not you have
DEBUG=True
, either show a detailed debugging page, or mail the exception to the users mentioned in theADMINS
setting.Secondly, you should never be getting a Webfaction error page - I can't even imagine how that is happening. If you want your users to see a nice error page, you should define 404.html and 500.html templates, or even full error-handling views if your needs are more complicated. This is fully explained in the documentation.
当有事情发生时,使用 mail_admins 给自己发邮件怎么样?
例如
How about using mail_admins to mail yourself when something's up?
eg