Django ajax error response best practice

后端 未结 5 1602
情书的邮戳
情书的邮戳 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:42

    Use option 1 but not entirely the way you describe it, you should return a HttpResponse with status_code 200 indicating in the response content (using JSON or some text) that a validation error occurred, then, when you process the response on the client with JQuery just check for the response content and detect if there were validation errors.

    Example of JSON string for the HttpResponse:

    {"errors": "true", "messages": ["Error #1", "Error #2", "etc."]}
    

    Option 2 is not a good practice because internal server errors happens when there is an uncaught exception that that was thrown by the server and commonly is unknown to the programmer.

    Don't use HTTP status codes to denote validation errors, that is not their purpose.

提交回复
热议问题