Angular - 如何正确处理来自服务器的 HTTP 错误?

Angular - How to properly handle an HTTP error from server?

目前我有这个:

$http({
    method: 'POST',
    url: 'http://api-endpoint/somescript/',
    data: formData,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})
.then(function (response) {
    console.log(response);
});

如果另一端的脚本运行正常,则会调用 then。但是,假设服务器端的脚本有某种错误没有被正确捕获。如果我通过抛出一些像 asdfasdf() 这样的垃圾调用来弥补错误,则不会调用 then 函数,而是在浏览器控制台中得到这个:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://api-endpoint/somescript/. (Reason: CORS
header 'Access-Control-Allow-Origin' missing).

如何在 Angular 代码中捕捉到它,以便我可以以用户友好的方式处理它?

编辑:这不是重复的,因为它特定于 Angular。

为了处理这个问题,我们必须添加一个 service/factory 来拦截 http 调用。你可以在你的配置中这样做

$httpProvider.interceptors.push('httpRequestInterceptor'); 

现在,上面的服务将是这样的

angular.module("app").factory('httpRequestInterceptor', function ($q) {

            return {
                'request': function (config) {

                    // Extract request information
                    return config || $q.when(config);
                },
                'responseError': function(rejection) {

                    // Extract response error information and handle errors
                    return $q.reject(rejection);
                 }
             }
        });

$q.then() 方法接受三个函数参数,第一个是成功回调的处理程序,第二个是错误,第三个是通知。 $http 在幕后利用了 $q,因此 thenable 的行为应该与文档中建议的一样。

要处理上面代码中的错误,只需加入一个额外的函数来处理错误:

.then(function (response) {
    console.log(response);
}, function(response) {
    console.log(response);
});

请随意浏览 $q 文档,特别是 The Promise API,了解更多详细信息。