Django ajax error response best practice

后端 未结 5 1526
情书的邮戳
情书的邮戳 2021-02-03 10:16

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. valid
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-03 10:55

    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. It violates good HTTP practice. There is a reason why there are plenty of error-codes defined

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

    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.

提交回复
热议问题