简体   繁体   English

javascript可观察的错误处理

[英]javascript observable error handling

I am trying to generate custom error handling when my observable fails instead of getting a big 404 error in my console. 我尝试在可观察项失败时生成自定义错误处理,而不是在控制台中收到较大的404错误。 However, no matter how many tutorials I read I jsut can't figure out how it works. 但是,无论我阅读了多少本jsut教程,都无法弄清楚它是如何工作的。

my code is as follows: 我的代码如下:

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

The success statement works, however the fail method doesn't. 成功语句有效,但是fail方法无效。

Here is the call that I make to the ,icrosoft graph endpoint: 这是我对.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;
        }

on success it returns: succesful call blob: http://localhost:8480/7da29a36-d13d-440f-8207-75f1cde58fcf 成功返回:成功调用blob: http:// localhost:8480 / 7da29a36-d13d-440f-8207-75f1cde58fcf

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

Have you tried this: 您是否尝试过:

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

?

The success statement works, however the fail method doesn't. 成功语句有效,但是fail方法无效。

.getUserProfilePicture returns a promise. .getUserProfilePicture返回一个承诺。 A promise either succeeds (resolved) or fails (rejected). 一个诺言要么成功(解决),要么失败(拒绝)。 If getUserProfilePicture resolves even by passing invalid data then it has bugs. 如果getUserProfilePicture甚至通过传递无效数据来解决问题,则说明存在错误。 Your posted code has no problem regarding handling promises' different states. 您发布的代码在处理诺言的不同状态方面没有问题。

If you want to reject the promise manually you can throw an error in your success handler: 如果要手动拒绝承诺,则可以在成功处理程序中引发错误:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM