Python 如何处理 Django 中的数据库异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14195544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle database exceptions in Django
提问by Prometheus
I want to known the best way to handle database exceptions and display messages back to the user. I have been looking at messages.add_messagein my views using a try.
我想知道处理数据库异常并向用户显示消息的最佳方法。我一直在看messages.add_message我的看法,用了一个试试。
For example:
例如:
The following error (1062, "Duplicate entry '123321' for key 'PRIMARY'"). Display back to the user friendly message: "Error uploading CSV Duplicate entries"
以下错误(1062, "Duplicate entry '123321' for key 'PRIMARY'")。显示回用户友好的消息:"Error uploading CSV Duplicate entries"
Is the the recommended way?
Are there any good tutorials on error handling (i.e. blog posts) that you would recommend as a good approach?
是推荐的方式吗?
是否有任何关于错误处理的好教程(即博客文章)您会推荐作为一种好方法?
采纳答案by arie
Database Exceptionsare documented,
check this answerto see an example of how to use them.
Database Exceptions已记录,请检查此答案以查看如何使用它们的示例。
If you are encountering this error while processing a formyou should probably handle the exception when validating your form. So in case an exception is raised you redisplay the formwith the appropriate error message.
如果您在处理表单时遇到此错误,您可能应该在验证表单时处理异常。因此,如果出现异常,您可以重新显示带有相应错误消息的表单。

