Search code examples
javascriptjsonajaxgetjson

getJSON error handling - using 2 APIs


firstly it's not another cross-domain error threads. I'm working on a simple webapp that uses two APIs (main & backup) to retrieve the same data from different servers. I use the following pattern:

//some functions and variables for DOM handling

$.getJSON(mainUrl, function(results) {

    //code to get and handle the data from main API

}).fail(function() { 

    $.getJSON(backupUrl, function(results) {

        //code to get and handle the data from backup API

    });
});

The problem is that the main API can fail in many ways:

  1. Doesn't respond - my code works fine as intended
  2. Responds, but due to external issue with API server, returns object with empty properties.

The second option is tricky, because it doesn't fit in the getJSON .fail scenario. The way I can handle is to add an if statement to check if object properties is not null and copy the code from backupAPI handler to retrieve the backup source, so it looks like this:

//some functions and variables for DOM handling

$.getJSON(mainUrl, function(results) {

     if (results.property) {

         //code to get and handle the data from main API

     } else {

         //code to get and handle the data from backup API
     }

}).fail(function() { 

    $.getJSON(backupUrl, function(results) {

        //code to get the data from backup API

    });
});

However, essentially I have the same block of code in two places of my main.js file, and it doesn't seem to be a good practice.

Could you guys help me solve the case properly to avoid putting the same code twice around the place? Thank you.


Solution

  • What about placing the //code to get the data from backup API inside a function and then call that function wherever you'd have placed that code?

    You'd end up with something like

    //some functions and variables for DOM handling
    
    $.getJSON(mainUrl, function(results) {
    
         if (results.property) {
    
             //code to get and handle the data from main API
    
         } else {
    
             getJSONFromBackup();
         }
    
    }).fail(function() { 
    
        getJSONFromBackup();
    
    });
    
    function getJSONFromBackup(){
        $.getJSON(backupUrl, function(results) {
    
            //code to get the data from backup API
    
        });
    }