title: How to handle expected error in AJAX (including disclosing them to user)
body: <p>An expected error is one from the server that I anticipated or even raised by myself in the code. For example, when a user attempts to perform an action for which he has no sufficient privilege, I would raise <code>PermissionError</code> (a custom <code>Exception</code>) with a message describing the error. </p>
  
  <p>I have been searching for a good way to handle expected error for AJAX situation. The only requirement is to be able to display the error message to the user, as I want to keep my users in the loop of what's going on. </p>
  
  <p>My current approach is packaging the error message into a JSON object and send it back to the client-end</p>
  
  <pre><code>var ajaxResponse = $.ajax({
      ....        
  });
  
  ajaxResponse.done(function(jsonObj) {
      if (jsonObj.success) {
          /* no error, do something */    
      }
      else {
          /* expected error returned, display jsonObj.error to user */
      }
  });
  
  ajaxResponse.fail(function(jqXHR, textStatus, errorThrown) {
      /* unexpected error returned */
  });
  </code></pre>
  
  <p>I have another approach in mind, which I am not sure about. Basically, instead of packaging the message of expected error into a JSON object, in my django code I would return <code>HttpResponse(content="no sufficient privilege", status=403)</code>. The client-end jQuery would get modified like the following:</p>
  
  <pre><code>ajaxResponse.done(function(response_data) {
      /* no error, do something */
  });
  
  ajaxResponse.fail(function(jqXHR, textStatus, errorThrown) {
      /* both expected and unexpected error would end up here.
       * It's an expected error when error code is 403 and 
       * jqXHR.responseText would give me the error message to 
       * display to the user.
       */
  });
  </code></pre>
  
  <p>I like how the second approach groups all errors, expected or unexpected, in one place. But then, I have a feeling that http status code shouldn't be used this way. Anyways, I want to know which one is the right way to go. If neither, please share what you would do. </p>