我的代码有问题。
if (command === 'channel'){
if (args.length == 0 ){
return message.channel.send(Aucun argument trouvé)
}
await message.guild.channels
.create(args[0] ,{
type : 'text' ,
})
.then((chan)=>{
var data = fs.readFileSync('test.json')
var parsedata = JSON.parse(data)
var test = 0
console.log(parsedata['category'])
try {
chan.setParent( parsedata['category'])
}catch{
message.channel.send("il s'emblerais que la commande category est mal été configuré ")
channel.delete()
console.log("end")
return
}
});
message.channel.send("channel "+args[0]+" crée :)")
};
我正在尝试创建一个频道并将其移至一个类别。类别 ID 存储在名为 test.json
的文件中。
我的问题是,如果存储的 ID 不存在,那么 try-catch 应该停止错误并执行 catch
块中的代码。
但事实并非如此。
这里是错误:
node:15548) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
parent_id: Category does not exist
at RequestHandler.execute (c:\Users\etoile\Desktop\ts bot js\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (c:\Users\etoile\Desktop\ts bot js\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
at async TextChannel.edit (c:\Users\etoile\Desktop\ts bot js\node_modules\discord.js\src\structures\GuildChannel.js:355:21)
(Use node --trace-warnings ... to show where the warning was created)
<node_internals>/internal/process/warning.js:42
(node:15548) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
<node_internals>/internal/process/warning.js:42
(node:15548) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
提前感谢您的帮助
答案 0 :(得分:1)
您收到错误,因为父类别不存在。如果要捕获此错误,则需要在 await
前使用 chan.setParent()
关键字(因为 .setParent()
方法是异步的):
if (command === 'channel') {
if (args.length === 0) return message.channel.send('Aucun argument trouvé');
try {
let chan = await message.guild.channels.create(args[0], {
type: 'text',
});
let data = fs.readFileSync('test.json');
let parsedata = JSON.parse(data);
await chan.setParent(parsedata['category']);
message.channel.send(`channel ${args[0]} crée :)`);
} catch {
message.channel.send(
"il s'emblerais que la commande category est mal été configuré",
);
// not sure what channel you want to delete here
channel.delete();
}
}