javascriptjqueryjqxhr

Handling API http return errors on JQuery


I have this html page:

$(document).ready(function() {

  $.ajax({
    url: "https://api.github.com/users/Microsoft/",
    type: 'GET',
    dataType: 'json',
    success: function(res) {
      $('#result').text(JSON.stringify(res, null, '\n'));
    }.error: function(jqXHR, error, errorThrown) {
      if (jqXHR.status && jqXHR.status == 400) {
        alert(jqXHR.responseText);
      } else {
        alert("Something went wrong");
      }
    }
  });

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="container">
  <pre id="result" style="color:red"></pre>
</div>

If Take away this:

.error: function(jqXHR,error, errorThrown) {  
           if(jqXHR.status&&jqXHR.status==400){
               alert(jqXHR.responseText); 
           }else{
               alert("Something went wrong");
           }

The result is shown properly, right now, it doesn't show anything. Just a blank page.

What I want, is to handle some http error that could happen if the API response isn't successful.

Any ideas?


Solution

  • Typo where you define error method:

    $(document).ready(function() {
    
      $.ajax({
        url: "https://api.github.com/users/Microsoft/",
        type: 'GET',
        dataType: 'json',
        success: function(res) {
          $('#result').text(JSON.stringify(res, null, '\n'));
        },
        error: function(jqXHR, error, errorThrown) {
          if (jqXHR.status && jqXHR.status == 400) {
            alert(jqXHR.responseText);
          } else {
            alert("Something went wrong");
          }
        }
      });
    
    })