NodeJS包:错误处理

时间:2017-07-11 19:53:24

标签: javascript node.js error-handling

我有一些代码使用Overwatch API来获取一些数据。这就是我目前所拥有的:

OWoverallStats: (playerName, mode, region) => {
    mode = (typeof mode === 'undefined') ? 'competitive' : mode.toLowerCase();
    region = (typeof region === 'undefined') ? 'us' : region.toLowerCase();

    playerName = playerName.replace('#', '-');

    return fetch(`https://owapi.net/api/v3/u/${playerName}/stats`)
        .then(res => res.json())
        .then(data => {
            return data[region].stats[mode].overall_stats;
        });
}

这样可以正常工作,只需输入实际存在的playerName即可。我用来测试它的代码是:

core.OWoverallStats('Calvin-1337', 'quickplay', 'eu').then(data => {
    console.log(data.tier) // grandmaster
}).catch(e => {
    console.log(e);
});

在实际代码中,我可以检查错误代码是否为404(玩家不存在)但是我不知道我能用它做什么。我不想抛出错误,或者控制台记录它,好像有人在Discord Bot中实现了这个,我希望使用该代码的人说出他们想要对错误做什么。< / p>

1 个答案:

答案 0 :(得分:0)

当fetch有响应时,如果状态为404 Simply throw a Error。然后,您的代码的调用者可以捕获它并处理他喜欢的。

例如,您的代码:

return fetch(`https://owapi.net/api/v3/u/${playerName}/stats`)
.then((res, meta) => {if (meta.status ===404) throw new Error('NoPlayer')})

您的代码的来电者:

core.OWoverallStats('Calvin-1337', 'quickplay', 'eu').then(data => {
}).catch(e => {
//this is where he can handle the error flexibly
});

您可能会看到other error handling practices here