Django ajax error response best practice

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

    I would take neither of your suggested approaches. I would suggest something along the lines of what Sid said. Why would you not want to write error free code?

    I would try to address all possible bugs and errors in the code I write at all times. This includes validating user input. With ajax i think it is important to send the messages back to the user. This is easily accomplished with json.

    response_dict = {}
    try:
       # do action that could cause an error
    except ExpectedError as e:
       response_dict['success'] = False
       response_dict['message'] e.msg # or custom message
       return HttpResponse(json.dumps(repsonse_dict))
    

    then in your ajax call back make sure the response is valid, if it is not alert the user of what they have done wrong. don't leave them hanging you are making an app for them!

提交回复
热议问题