[Django]-How should error corresponding to an AJAX request be passed to and handled at the client-side?

2đź‘Ť

âś…

The best practice would probably be to return an error object like this:

{error:true,
 errorCode:123,
 errorMessage:"Duplicate Email",
 errorDescription:"The email you entered (john@johndoe.com) already exists"
}

Then you can track a list of error codes/messages specific to your application.

👤citizen conn

11đź‘Ť

If you want to do it the Right Way™, make your services RESTful. In this case, the appropriate status code is probably “409 Conflict”, which Wikipedia defines as “Indicates that the request could not be processed because of conflict in the request, such as an edit conflict”. (See also REST HTTP status codes for failed validation or invalid duplicate.)

So have your server output a “409 Conflict” header, and in your client, check status. $.post() won’t do it as you can only register a success handler, so you’ll need to use $.ajax() like this:

$.ajax({
  statusCode: {
    409: function() {
      alert('duplicate');
    }
  }
});
👤mahemoff

Leave a comment