Django的Ajax错误反应的最佳实践 [英] Django ajax error response best practice

查看:572
本文介绍了Django的Ajax错误反应的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Ajax来改善我的Django项目的用户体验。在这里我关心的是如何正确应对错误的浏览器。据我知道,我可以:

I'm using ajax to improve user experience in my Django project. My concern here is how to respond error to browser properly. As far as I know, I can either:

  1. 验证请求数据逐件和防范异常一个接一个。如果有什么不好的事情发生,提高HTTP404或其他异常明确地宣布发生了错误。或
  2. 只写code没有异常处理,并假设它会工作。如果有什么不好的事情发生,未捕获的异常会导致内部服务器错误,这仍是浏览器
  3. 错误

对于我来说,最前一页方法似乎比较正统,因为在Python的理念,以显式优于隐式真正重要的。但是,由于种种异常检查是从第二个删除,它是清洁,少分散,更具有可读性。

For me, the fisrt method seems more orthodox , as in Python the philosophy of "Explicit is better than Implicit" really counts. But since all sorts of exception checking are removed from the second one, it is cleaner, less fragmented and more readable.

我使用jQuery来处理Ajax请求/响应,这两种方法似乎工作。我的问题是:

I'm using jQuery to handle ajax request/response and both methods seem working. My questions are:

  1. 是这两种方法是否可以接受?
  2. 将用于其他JavaScript库的第二种方法失败了呢?
  3. 什么是最好的做法呢?

PS。我做的做的重要的数据验证。请不要偏离为主题。 :)

PS. I do do essential data validation. Please do not stray the topic for that. :)

推荐答案

如果您返回与4XX或5XX状态code的响应,这是一个错误,并会引发jQueries 错误处理程序。虽然这当然是可能的,每次简单返回状态200,并在JSON响应使用一个错误字段(如由dm03514所建议的),这是不好的,原因有二:

If you return a response with a status code of 4xx or 5xx this is a an error and will trigger jQueries error handler. While it is certainly possible to simple return status 200 every time and use a "error" field in the JSON response (like suggested by dm03514) this is bad for two reasons:

  1. 这违反了良好的HTTP做法。有一种的的原因的原因有很多错误 - codeS的定义

  1. It violates good HTTP practice. There is a reason why there are plenty of error-codes defined

您不能使用jQuery的已经有一个错误处理程序,可以让你分开的错误处理正常行为的事实。

You can't use the fact that jQuery already has a error-Handler that lets you separate normal behavior from error handling.

在大多数情况下的错误响应将是来自非错误响应太大不同,因此它根本是没有意义的把这个邮件的处理方式在一块的JS code。因此,要总结的东西了,请使用状态200 JSON响应为您的正常响应并返回一个错误(在适当的!)4XX / 5XX响应。这些可以携带JSON有效载荷,也让你的服务器端可添加了错误的详细信息。

Most of the time the error response will be much different from the non-error response So it simply makes no sense to put the handling of this messages in one piece of JS code. So, to sum things up, use a JSON response with status 200 for your normal responses and return a (appropriate!) 4xx/5xx response for errors. These can carry JSON payload, too, so your server side can add additional details about the error.

这篇关于Django的Ajax错误反应的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆