How to handle server-side errors correctly?

I am developing a web application using angular.js, currently I am a little confused about how to handle errors correctly. In my application, I used ngResource to call the shutdown API on the server. Therefore, I will have many calls to niResource api.

eg. user resource, user user.query (), user.get (), user.save () ...... Do I have to rely on the error callback in all api calls to ngResource? Just to handle all kinds of errors: for example, is the server down or is there no Internet access?

I just don't think the error callback in every ngResource api call is a good idea. This will create a lot of redundant code and make my code tidy.

What will you do to handle the various types of errors?

+4
source share
1 answer

You can use an interceptor and do whatever you want when an error occurs:

var app = angular.module("myApp", []);

app.config(function ($provide, $httpProvider) {
    $provide.factory('ErrorInterceptor', function ($q) {
        return {
            responseError: function(rejection) {
                console.log(rejection);
                return $q.reject(rejection);
            }
        };
    });

    $httpProvider.interceptors.push('ErrorInterceptor');
});

With this interceptor, you can read the status code and do what you need (the ideal use case is to redirect the user to the login page if the status code is 401).

Since ngResource uses $ http, your hooks will also execute when the resource method is called.

Of course, you can do more and add an interceptor before / after the request.

See the full documentation here: http://docs.angularjs.org/api/ng.$http

See this script: http://jsfiddle.net/4Buyn/ for a working sample.

+8

All Articles