Django ajax error response best practice

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

    I can't answer whether both methods are acceptable but can only tell you what I do. In my view I catch some specific/explicit errors such as:

    • Invalid or missing params in post
    • High level errors such as username already present in database (in a signup situation for e.g.)
    • All other system errors

    I think if you categorize your errors as some specific errors that the user must know about and then everything else then your code will have at the most 2 or 3 return with error routes, which IMHO isn't so bad. I use JSON to return errors and my structure is usually such:

    respons={}
    response["error|ok"]
    response["msg"]="User not found"
    response["type"]=ERROR_TYPE # only applicable for errors
    

    Obviously this is quite basic but hopefully gives you a general idea. I would recommend against letting the user see the system generated internal server error. That is horrible user experience, even for internal apps.

    Hope this helps.

提交回复
热议问题