javascript可观察的错误处理

时间:2017-11-07 12:05:22

标签: javascript observable

我正在尝试在我的observable失败时生成自定义错误处理,而不是在我的控制台中出现大404错误。但是,无论我阅读了多少教程,我都无法弄清楚它是如何工作的。

我的代码如下:

datacontext.graph.getUserProfilePicture('', detailedData.id)
.then(function success(photo) {
    console.log("succesful call" + photo);
})
.catch(function error(err) {
    console.log("error" + err);
});

成功声明有效,但失败方法没有。

以下是我对icrosoft图终端的调用:

function getUserPic(principalName) {
            var deferred = $q.defer();
            var endpoint = config.baseGraphApiUrl + "users/" + principalName + "/photo/$value";
            $http.get(endpoint, { responseType: 'blob' }).then(function (result) {
                var file = new Blob([result.data], { type: 'image/jpeg' });
                var fileURL = URL.createObjectURL(file);

                deferred.resolve(fileURL);
            }, function (data) {
                console.log(error);
            });

            return deferred.promise;
        }

成功后返回: 成功召唤blob:http://localhost:8480/7da29a36-d13d-440f-8207-75f1cde58fcf

失败后返回:  https://graph.microsoft.com/v1.0/users/63c31121-cd15-4f48-ba43-8dea613f19cd/photo/ $ value 404(未找到)

2 个答案:

答案 0 :(得分:0)

你试过这个:

.then(function success(photo) {
    console.log("succesful call" + photo);
}, function(err){
    console.log("error" + err);
})

答案 1 :(得分:0)

  

成功声明有效,但失败方法没有。

.getUserProfilePicture返回一个承诺。承诺要么成功(已解决),要么失败(被拒绝)。如果getUserProfilePicture即使通过传递无效数据也会解决,那么它就会出现错误。您发布的代码在处理承诺方面没有任何问题。不同的州。

如果您想手动拒绝承诺,可以在成功处理程序中抛出错误:

datacontext.graph.getUserProfilePicture('', detailedData.id)
.then(function success(photo) {
    console.log("succesful call" + photo);
    throw new Error('I am an error!');
})
.catch(function error(err) {
    console.log("error" + err);
});
相关问题