所以我是Javascript的新手,正在尝试制作一个不和谐的机器人。下面是说明我的问题的一小部分:
module.exports = {
name: "match",
category: "LOL",
description: "Give Summoner's Data to User",
run: async (client, message, args) => {
var username = `${args}`
var regionID= "na1"
pyke.summoner.getBySummonerName(username, regionID).then(data => {
return pyke.spectator.getCurrentGameInfoBySummoner(`${data.id}`, "na1").then(result => {
try {
console.log(result)
} catch (err) {
console.error(`${args} isn't in game!`)
}
})
})
}
}我被期望看到一个错误的原因,它会发送一个代码到控制台。但是,我得到了一个UnhandledPromiseRejectionWarning。我的问题是,为什么我不能捕获错误并向控制台发送代码?
这就是我尝试使用的命令
const property1 = result.participants.summonerName
const BResult = property1
let FResult = JSON.stringify(BResult)
message.channel.send(FResult)当我尝试时,我得到了一个错误,说这个人不在游戏中。我知道这是错误的,因为他们在游戏中。
所以我走得更远,试着这样做。
const property1 = result.participants[summonerName]
const BResult = property1
let FResult = JSON.stringify(BResult)
message.channel.send(FResult)我仍然得到与上一次相同的结果。我也尝试做const property1 = result.summonerName,但效果不佳。
发布于 2020-07-19 00:57:36
相反,尝试将pyke.spectator.getCurrentGameInfoBySummone包装在try/catch中。此示例使用带有await关键字的try/catch:
module.exports = {
name: "match",
category: "LOL",
description: "Give Summoner's Data to User",
run: async (client, message, args) => {
const username = `${args}`;
const regionID = "na1";
return pyke.summoner.getBySummonerName(username, regionID).then((data) => {
try {
const result = await pyke.spectator.getCurrentGameInfoBySummoner(`${data.id}`, "na1");
console.log(result);
} catch (err) {
console.error(`${args} isn't in game!`);
}
});
},
};否则,您可以尝试仅使用Promise catch来处理错误:
module.exports = {
name: "match",
category: "LOL",
description: "Give Summoner's Data to User",
run: async (client, message, args) => {
const username = `${args}`;
const regionID = "na1";
return pyke.summoner.getBySummonerName(username, regionID).then((data) => {
return pyke.spectator.getCurrentGameInfoBySummoner(`${data.id}`, "na1")
.then(result => {
console.log(result);
})
.catch(err => {
console.error(`${args} isn't in game!`)
});
});
},
};您可以使用JSON.stringify来字符串化对象,并且可以使用各种不同的方法(如destructuring )来提取您只想在创建/返回新对象时返回的特定属性:
// extract specific properties from `result`
// This is use ES6 destructuring, but you can use dot notation instead or whatever you prefer
const { property1, property2, property 3 } = result;
// return the stringified object only with the properties you need
const payload = { property1, property2 ,property };
return JSON.stringify(payload)https://stackoverflow.com/questions/62971190
复制相似问题