[英]NodeJS Package: 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中一样,我希望使用代码的人说出他们想对错误做些什么。
当获取具有响应时,如果状态为404,则仅引发错误。 然后,您的代码调用者可以捕获它并按自己喜欢的方式进行处理。
例如,您的代码:
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.