Javascript – Best practice for angular service return value

angularjserror handlingjavascript

I have a number of angular services (e.g. a user service) which make various HTTP calls and I'm wondering what the best practice would be for handling errors. For example, I could do:

function getAll(success, error) {
    $http.get('/api/users').then(success, error);
}

Or I could do:

function getAll(success) {
    $http.get('/api/users').then(success, function(err) {
        success([]);
    });
}

The advantage of the former is it is more configurable in case I wanted to do something special. However, the advantage of the second is that it keeps the controllers simpler and in the (hopefully rare) case that the server is down it won't simply throw an error but will just display blank/empty data.

Is there any guideline or accepted best practice for this kind of situation?

Best Answer

My preferred pattern is that the api layer returns a promise which is resolved if the call is successful (whether it found any data or not) and rejected only if the call failed.

A call to getCurrentUser for instance is supposed to either return a user or tell me that user doesn't exist or that I don't have adequate permissions or various other things. If it does any of those things it is supposed to do, the api call itself is successful and the result should be passed back to the caller. If instead, I get a 4xx or 5xx error code, then the call itself failed and the caller should be notified.

Let the api layer worry about making the call and returning the data. Let the data layer worry about interpreting the data and updating models. Let the UI layer about presenting the data and notifying the user if there was an error.

Related Topic