How to properly handle server side errors?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-05 02:41:00

问题


I'm developing web app with angular.js, I'm currently a little confused about what's the proper way to handle errors. In my app, I have used ngResource to call rest API of server. So I'll have a lot of ngResource api calls.

e.g. user resource, there're user.query( ), user.get( ) , user.save( ) ...... Do I suppose to put an error callback into all of the ngResource api calls? Just to handle all kinds of errors: like server down or no internet access ??

I just don't think put an error callback in every ngResource api call is a good idea. That'll produce a lot of redundant code and make my code not neat .

What will you do to handle various error types?


回答1:


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

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 (a perfect use case is to redirect your user to a login page if status code is 401).

Since ngResource use $http, your interceptors will also be executed when you call a resource method.

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

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

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



来源:https://stackoverflow.com/questions/21254714/how-to-properly-handle-server-side-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!