首先,您应该考虑要暴露哪些错误:
通常会披露4xx错误(归因于客户端的错误),以便用户可以更正请求。
另一方面,通常仅在没有信息的情况下显示5xx错误(归因于服务器端的错误)。在我看来,对于那些您应该使用诸如Sentry之类的工具来监视和解决此错误,这些错误中可能嵌入了安全性问题。
在我看来,考虑到正确的Ajax请求,您应该返回一个状态码,然后返回一些json以帮助理解发生了什么,例如消息和解释(适用时)。
如果您的目标是使用Ajax提交信息,建议您为所需内容设置一个表格。这样,您就可以轻松地通过一些验证过程。我将在示例中假设情况是这样。
首先 -请求正确吗?
def test_view(request): message = None explanation = None status_pre = 500 # First, is the request correct? if request.is_ajax() and request.method == "POST": .... else: status_pre = 400 message = "The request is not valid." # You should log this error because this usually means your front end has a bug. # do you whant to explain anything? explanation = "The server could not accept your request because it was not valid. Please try again and if the error keeps happening get in contact with us." return JsonResponse({'message':message,'explanation':explanation}, status=status_pre)第二 -表格中是否有错误?
form = TestForm(request.POST)if form.is_valid(): ...else: message = "The form has errors" explanation = form.errors.as_data() # Also incorrect request but this time the only flag for you should be that maybe Javascript validation can be used. status_pre = 400
您甚至可能逐字段获取错误,因此可以在表单本身中以更好的方式呈现。
第三 -让我们处理请求
try: test_method(form.cleaned_data) except `PermissionError` as e: status_pre= 403 message= "Your account doesn't have permissions to go so far!" except `Conflict` as e: status_pre= 409 message= "Other user is working in the same information, he got there first" .... else: status_pre= 201 message= "Object created with success!"
根据您定义的例外,可能需要不同的代码。转到Wikipedia并检查列表。不要忘记,响应的代码也不同。如果您向数据库中添加内容,则应返回
201。如果您只是获得信息,那么您正在寻找GET请求。
回答问题
如果不处理,Django异常将返回500个错误,因为如果您不知道会发生异常,那么这是服务器中的错误。除了404和登录要求外,我将对
try catch
所有内容进行阻止。(对于404,您可以将其提高,如果您这样做@login_required
或获得所需权限,django会在不执行任何操作的情况下以适当的代码进行响应)。我不同意这种方法。正如您所说,错误应该是明确的,因此您应该始终知道将要发生的情况以及如何进行解释,并使其取决于所执行的操作。
我会说400错误是可以的。您只是需要解释原因,这是一个错误的请求,错误代码适合您和您的js代码,因此请保持一致。
(提供示例)-在第三个示例中,
text_view
您应具有test_method
。
测试方法应具有以下结构:
def test_method(validated_data): try: my_business_logic_is_violated(): catch BusinessLogicViolation: raise else: ... #your pre
在我的示例中:
try: test_method(form.cleaned_data) except `BusinessLogicViolation` as e: status_pre= 400 message= "You violated the business logic" explanation = e.explanation ...
我认为违反业务逻辑是“客户端错误”,因为如果在该请求之前需要进行某些操作,则客户端应该意识到这一点,并要求用户先执行此操作。(来自错误定义):
400(错误请求)状态码表示服务器由于某些原因(例如格式错误的请求语法,无效的请求
消息框架或欺骗性的请求路由)而被视为客户端错误,因此服务器无法处理该请求。
顺便说一句,您可以查看有关用户定义的异常的Python文档,因此您可以提供适当的错误消息。该示例背后的想法是,您会根据生成
BusinessLogicViolation消息
my_business_logic_is_violated()的位置引发异常,并带有不同的消息。



