因此,我是Java的新手,正在尝试制作一款不和谐的机器人。这是说明我的问题的一小部分:
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
,但效果不佳。
答案 0 :(得分:2)
请尝试将pyke.spectator.getCurrentGameInfoBySummone
包装在try/catch
中。本示例将try/catch
与await
关键字一起使用:
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)