[英]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.