给出错误但仍然正常运行

时间:2018-03-23 19:43:56

标签: promise bots discord.js

在我从另一个用户那里得到同一行代码的帮助之后,一个新的“错误”浮出水面。即使记录了错误,它仍然可以找到一种方法来使我的代码工作。如果有解决方案,请告诉我,但如果没有,请解释原因。我希望这不会发生,即使它可能不会导致任何问题,但它更好,以便我可以阅读更多重要的错误,这将导致我的代码出现问题。这是我的代码:

const Discord = require('discord.js');
const botconfig = require("./botconfig.json");
const fs = require("fs");
const bot = new Discord.Client();
bot.on("message", async message => {
    let prefix = botconfig.prefix;
    let messageArray = message.content.split(" ");
    let cmd = messageArray[0];
    let args = messageArray.slice(1);
    console.log(message.member.id)
    var playerFile = JSON.parse(fs.readFileSync(`./playerData/${message.member.id}.json`, "utf8"));
    if (cmd === `${prefix}fc`) {
        fs.exists(`./playerData/${message.member.id}.json`, function(exists) {
            if (exists) {
                let ar = args[0];
                let ninConsole = args[1];
                let code = args[2];
                if (ar === "add" || ar === "remove") {
                    if (code) {
                        if (ar === "add") {
                            console.log("Add");
                            if (ninConsole === "switch") {
                                console.log("Switch " + code);
                                let fileContent = `{"switch": "${code}","threeDS": "${playerFile.threeDS}"}`
                                fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
                                    if (err) {
                                        console.error(err);
                                        return;
                                    };
                                    message.delete();
                                });
                            }
                            if (ninConsole === "3ds") {
                                let fileContent = `{"switch": "${playerFile.switch}","threeDS": "${code}"}`
                                fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
                                    if (err) {
                                        console.error(err);
                                        return;
                                    };
                                    message.delete();
                                });
                            }
                        } else if (ar === "remove") {
                            if (ninConsole === "switch") {
                                let fileContent = `{"switch": "None","threeDS": "${playerFile.threeDS}"}`
                                fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
                                    if (err) {
                                        console.error(err);


                         return;
                                };
                                message.delete();
                            });
                        }
                        if (ninConsole === "3ds") {
                            let fileContent = `{"switch": "${playerFile.switch}","threeDS": "None"}`
                            fs.writeFile(`./playerData/${message.member.id}.json`, fileContent, (err) => {
                                if (err) {
                                    console.error(err);
                                    return;
                                };
                                message.delete();
                            });
                        }
                    }
                }
            } else {
                console.log('Got to here');
                let codeEmbed = new Discord.RichEmbed()
                    .setTitle(`${message.author.username}'s FriendCodes`)
                    .setColor('#FDB25F')
                    .addField('Switch Code', playerFile.switch, true)
                    .addField('3DS Code', playerFile.threeDS, true)
                    .setFooter('Deleting in 30 seconds...')
                message.channel.send(codeEmbed)
                    .then(msg => {
                        msg.delete(30000)
                    });

            }
        } else {
            return message.delete();
        }
    });
}
// ...

这是错误:

(node:27903) UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open './playerData/425674570851418113.json'
    at Object.fs.openSync (fs.js:646:18)
    at Object.fs.readFileSync (fs.js:551:33)
    at Client.bot.on (/home/yello/Desktop/Bot/index.js:45:40)
    at emitOne (events.js:116:13)
    at Client.emit (events.js:211:7)
    at MessageCreateHandler.handle (/home/yello/Desktop/Bot/node_modules/discord.js/src/client/websocket/packets/handlers/MessageCreate.js:9:34)
    at WebSocketPacketManager.handle (/home/yello/Desktop/Bot/node_modules/discord.js/src/client/websocket/packets/WebSocketPacketManager.js:103:65)
    at WebSocketConnection.onPacket (/home/yello/Desktop/Bot/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (/home/yello/Desktop/Bot/node_modules/discord.js/src/client/websocket/WebSocketConnection.js:296:17)
    at WebSocket.onMessage (/home/yello/Desktop/Bot/node_modules/ws/lib/event-target.js:120:16)
(node:27903) 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(). (rejection id: 1)
(node:27903) [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.

1 个答案:

答案 0 :(得分:1)

订单错误。
您正在尝试解析该文件,然后检查该文件是否存在:

console.log(message.member.id)
var playerFile = JSON.parse(fs.readFileSync(`./playerData/${message.member.id}.json`, "utf8"));
if (cmd === `${prefix}fc`) {
    fs.exists(`./playerData/${message.member.id}.json`, function(exists) {
        if (exists) {
            let ar = args[0];

但是你需要首先检查文件是否存在,然后阅读并解析它。所以它会是这样的:

console.log(message.member.id)
if (cmd === `${prefix}fc`) {
    fs.exists(`./playerData/${message.member.id}.json`, function(exists) {
        if (exists) {
            var playerFile = JSON.parse(fs.readFileSync(`./playerData/${message.member.id}.json`, "utf8"));
            let ar = args[0];