AngularJS deal with API errors on a per resolve basis

Issue

I am using AngularJS with UI-Router to make a Single Page App which calls out to a REST API for json data.

I have a app.config like this:

.state('project', {
    url: '/project/:projectId/',
    views: {
        'main': {
            templateUrl: 'partials/project.tmpl.html',
            controller: 'ProjectCtrl',
            resolve: {
                project: function ($stateParams, APIService) {
                    return APIService.get('projects/', $stateParams.projectId);
                },
                userprofiles: function (APIService) {
                    return APIService.list('userprofiles/');
                },
            }
        },
    }
}) 

And I am handling API errors using the app.run:

.run( function ($http, $cookies, $state, $rootScope) {
    $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams, error) {
        $state.get('error').error = error;
        return $state.go('error');
    });
});

Now, this works great and any 404s form my API can easily be haded off to an error state and a corresponding Controller and Template.

However, what I would like is that if a 404 is returned from the projects API endpoint I get this behaviour (as it is part of the url), but if an error is returned from the userprofiles API endpoint I can return, say and empty object, and handle that error in the controller. This 404 could be considered non-critical where the 'projects 404 would be.

What would be my best approach to this? As I build this out I expect I will want to be able handle certain API errors in their respective controllers and some at the global level.

Solution

I’m assuming here that the APIService call returns a promise:

userprofiles: function (APIService) {
    // return the promise
    return APIService.list('userprofiles/').then(function(data){
        return data;
    },function(){ // and error occurred
        return {}; // return empty object on error.
    });
}

So long as you don’t return the error to the injected property being resolved the $stateChangeError shouldn’t occur.

Answered By – m.e.conroy

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.