ihasTaco / ServerQuery

A Discord Bot that queries game servers
Mozilla Public License 2.0
0 stars 0 forks source link

Add Error Handling to Prevent Server Crashes #6

Open ihasTaco opened 1 year ago

ihasTaco commented 1 year ago

In the current implementation of ServerQuery, an error during the reading or writing of a file can cause the entire server to crash. This is because the errors that occur during fs.readFile and fs.writeFile operations are not caught and handled, leading to unhandled exceptions that can terminate the server.

This issue can potentially make the server vulnerable to Denial of Service (DoS) attacks, as a malicious user might be able to cause an error that crashes the server.

To resolve this issue, we need to add error handling to all file operations to prevent unhandled exceptions from crashing the server. If an error occurs, it should be logged and an appropriate error response should be sent back to the client.

Steps to Reproduce:

Expected Outcome: The server should handle the error gracefully, log the error, and send back an error response to the client.

Actual Outcome: The server crashes due to an unhandled exception.

Suggested Fix: Add error handling to the fs.readFile and fs.writeFile callbacks. If an error occurs, log it and send an error response to the client. This will prevent unhandled exceptions from crashing the server. Refer to this post for best practices on error handling in Node.js.

Relevant Example Code Snippet: See postRoutes.js

router.post('/write-notification-settings/:guildID/:serverUUID', (req, res) => {
    const { guildID, serverUUID } = req.params;
    const notificationSettings = req.body;

    fs.readFile('./public/servers.json', 'utf8', (err, data) => {
        if (err) throw err;  // Unhandled exception

        // rest of the code...

        fs.writeFile('./public/servers.json', JSON.stringify(servers, null, 2), 'utf8', (err) => {
            if (err) throw err;  // Unhandled exception

            res.json({ message: 'Notification settings written.' });
        });
    });
});