试图捕获UnhandledPromiseRejectionWarning:错误:404 Not Found

问题描述 投票:-1回答:1

使用:https://www.npmjs.com/package/snekfetch我试图捕获以下错误:UnhandledPromiseRejectionWarning: Error: 404 Not Found

在网站上显示:{"error":"not-found"}

码:

const promise = new Promise(function(resolve, reject) {
    snekfetch.get('https://www.website.com/api/public/users?name=' + user).then(body => {
        const json = JSON.parse(body.text);
        const name = json.name;
        console.log(json);
        json ? reject(Error('It broke')) : resolve(name);
    });
});

promise.then((result) => {
    console.log(result);
    console.log('works');
}).catch((error) => {
    console.log(error);
    console.log('does not work');
});

我试图检查是否有json:json ? reject(Error('It broke')) : resolve(name);并且解决方案有效,但我似乎无法捕获404 Not Found错误,我该怎么做?

javascript json promise
1个回答
0
投票

问题是你正在绊倒the new Promise antipattern,而不是正确地传播错误。 :-)

修复它的正确方法是根本不使用new Promise

const promise = snekfetch.get('https://www.website.com/api/public/users?name=' + user)
    .then(body => {
        const json = JSON.parse(body.text);
        const name = json.name;
        return name;
    });

现在,promise将根据snekfetch的承诺解决或拒绝;如果它结算,它将使用JSON中的名称解析。 (我假设你真的需要解析JSON,snekfetch不会为你做。)

如果你有充分的理由在它周围包含另一个承诺(这里似乎没有一个),你需要确保你将错误从snekfetch的承诺传播到你的:.catch(reject)

// NOT APPROPRIATE HERE, but how you'd do it if you used an explicit new promise
const promise = new Promise((resolve, reject) => {
    snekfetch.get('https://www.website.com/api/public/users?name=' + user)
        .then(body => {
            const json = JSON.parse(body.text);
            const name = json.name;
            resolve(name);
        })
        .catch(reject);
});
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.