How to prevent signalR errors from stopping furthe

2019-06-08 10:03发布

问题:

I'm working on an asp.net mvc project where we use SignalR for real time connection in different views. Works great, apart from the fact that the execution of javascript stops if there's a problem with SignalR. Typically, this error would be a problem if my self hosting application is down, or other connection issues has occured.

GET http://localhost:8081/signalr/hubs net::ERR_CONNECTION_REFUSED List:328
Uncaught TypeError: Cannot read property 'client' of null 

As mentioned, if this has occured, it prevents all of my other javascript from executing, thus not rendering my views, or layout for that matter, properly. Is there a way to fix this, so the views continue to load and run its javascript?

My typical view would look like this:

@model Services.Models.SomeModel
<script src="~/Scripts/jquery.signalR-2.0.2.js"></script>
<script src="http://localhost:8081/signalr/hubs"></script>
<script src="~/Scripts/signalR.connector.js"></script>
<script src="~/Scripts/signalR.fleet.js"></script>
<div id="page-content">
    ...
</div>

Connector looks like this:

$.connection.hub.url = "http://localhost:8081/signalr";

//Enable logging
$.connection.hub.logging = true;

// Proxy created on the fly
var messageHub = $.connection.myHub;
if (messageHub == null)
    return null;

messageHub.client.timeEnabled = true;

... ommitted functions ...


$.connection.hub.start(function () {
        var id = $('#signalRId').text();
        messageHub.server.joinGroup("operationStatus-" + id);
        console.log("Joined group: operationStatus-" + $('#signalRId').text());
}).done(function () {
        console.log('Now connected, connection ID=' + $.connection.hub.id); 
        }
).fail(function () { console.log('Could not Connect'); });

回答1:

Not completely sure what you're asking for, but here are my thoughts - your basic tools are ...

  1. checking for problematic conditions

    if (messageHub) { 
        // set up client hub methods and start connection ...   
    } else {
        // /signalr/hubs script didn't load properly, so skip setting up signalr
    }
    
  2. using try/catch (for things that might cause problems but are less predictable); read jquery.signalR-* to see which errors might get thrown by the SignalR code

  3. a global error handler using window.onerror (also see this SO post):

    window.onerror = function(message, url, lineNumber) {
       console.log(message);
    };
    


回答2:

I had this problem as well. An easy way is to set a boolean in your done callback.

connected = true;

Then check before every request.

I have wrote me a lib that handel all my SignalR stuff and give me success and error callbacks. In this case I would get an errorCallback with content "not connected" or something. With a lib you have to write it only once.