Forum Moderators: open

Message Too Old, No Replies

Dealing with server errors when using EventSource

         

csdude55

6:14 am on Aug 7, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have a script that checks the logged in user's private messages and simply returns a total number of unread messages. It looks like this:

if ((iVal = $('#membersIcon')).length) {
// membersSSE and membersPath are defined elsewhere
if (typeof(EventSource) !== 'undefined') {
var source = new EventSource(membersSSE);

source.onmessage = function(e) {
$('#membersIcon').html(e.data);
if (e.id == 'CLOSE') { source.close(); }
};

source.onerror = function(e) {
if (e.readyState == EventSource.CLOSED) {

// backup plan, run membersPath every 15 seconds if membersSSE fails
iVal.ajax(membersPath);
setInterval("iVal.ajax(membersPath, 1)", 15000);
}
};
}


It works fine 99.9% of the time, but occasionally I see server errors in the console:

// for some reason the site wasn't responding
ERR_NAME_NOT_RESOLVED

// the connection timed out, probably on the user's end
ERR_CONNECTION_TIMED_OUT

// the user's IP changed, probably from a router reboot
ERR_NETWORK_CHANGED

There are probably other server errors that pop up, these are just the ones I've noted recently.

The errors are explicitly on membersSSE, though, and not membersPath, so it appears that they aren't triggering the source.onerror function.

Is there an error with the source.onerror function, or is there some other way to recognize server errors instead of script errors?