如何正确处理服务器端错误? [英] How to properly handle server side errors?

查看:122
本文介绍了如何正确处理服务器端错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发展与angular.js Web应用程序,我目前有点困惑什么是处理错误的正确方法。在我的应用程序,我已经使用ngResource调用服务器的REST API。因此,我将有很多的ngResource API调用。

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.

例如。用户资源,有很user.query(),user.get(),user.save()......
我想将错误回调到所有ngResource API调用?
只是为了处理各种错误:像服务器停机或无法上网?

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 ??

我不认为把一个错误回调每ngResource API调用是一个好主意。这会产生大量的冗余code,并让我的code不齐。

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?

推荐答案

您可以使用拦截器,做任何你想要的时候出现错误:

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');
});

通过这个拦截器可以读取状态code和你所需要的(一个完美的使用情况是你的用户重定向到登录页面,如果状态code为401)。

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).

由于ngResource使用的$ HTTP,你的拦截器也将当你调用一个资源方法执行。

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.

在这里查看完整文档: http://docs.angularjs.org/api/ng 。$ HTTP

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

看到这个小提琴: http://jsfiddle.net/4Buyn/ 以工作示例

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

这篇关于如何正确处理服务器端错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆