Saturday, April 21, 2012

SignalR: Handling results returned from server to JS

So, when we're calling server methods from our JS code, obviously, most of the times there will be some kind of result from this call - be it data returned from the server, or even if your method does not return any data - it can always return errors.
For the happy path scenarios, to get the data returned from the server just, we just need to call "done()" function of the object, returned from the hub method, and pass happy path callback to it.
hub.getOrders().done(function(orders){
    // populate some list with orders
});
In my initial post, I've used a different approach - I used a callback, which was called from server method, to return results to the client, simply because I was not aware of this "done()" method.
As for errors, you can access them too, using "fail()" function, like this:
hub.getOrders().done(function(orders){
    // populate some list with orders
})
.fail(function (e) {
    // handle error
});
The function parameter e contains the message of exception being thrown (that's the scenario I've tested) - or if it's just HTTP erorr - I'd guess it'll contain HTTP status message. It would be usefull to have a little bit more info in the fail method, like HTTP status code, or exception type name.

Hope this short post will be useful to someone looking how to handle errors.

No comments:

Post a Comment