vendredi 27 février 2015

Handling Socket.io to fail gracefully if the .js files cannot be loaded in with AJAX

I've built a simple Node Socket.io file that I'm using to post requests to to update a Perl application hooked up to it.


Example code in my Perl template file:



function start_io_service() {
socket = io("http://10.5.17.194:5892");
var current_user = $('#user-name').text();

console.log(socket); // For Debugging


// Handler to send back a username to the node application
socket.on('user-query', function (msg) {
// Send username
socket.emit('username', { username: current_user });
});
}


The Socket.io.js is loaded in using jQuery $getScript so I can handle if the Node server isn't running (which isn't required for 90% of the functionality of the Perl app).



$.getScript( "http://ift.tt/1EwBZ8z" )
.done(function( script, textStatus ) {
console.log( "It worked" );
})
.fail(function( jqxhr, settings, exception ) {
console.log("It didn't"); // This never appears
});


The .fail() method of getScript is completely ignored if the server isn't running when trying to load in the socket.io.js file from the server and I get the following error in my chrome console:



GET http://ift.tt/1LON9G7 net::ERR_CONNECTION_REFUSED


Even if I wrap the entire thing in a try and catch block it still doesn't change anything.


All I want is to ensure no errors appear and I get a simple console message instead. (The users of the system wouldn't be happy to see any sort of big red error message and would raise issues constantly).


Please note, if the server is running I get no issues and the app works, it's just handling the scenario that the server isn't running that I'm trying to solve.


Ideas?


Aucun commentaire:

Enregistrer un commentaire