OS.js icon indicating copy to clipboard operation
OS.js copied to clipboard

Prevent OSJS from Crashing on Uncaught Exceptions by Handling Errors Gracefully

Open maryam4s26 opened this issue 1 year ago • 5 comments

hello @andersevenrud In certain cases, some unhandled errors in the program are causing OS.js to crash unexpectedly. To improve the stability and prevent the entire system from going down due to unhandled exceptions, it might be beneficial to implement a global error handler.

For example, by adding the following code to the beginning of src/server/index.js, we can log the error without crashing OS.js:

process.on('uncaughtException', (error) => {
  console.log(error);
});

This approach would ensure that the server continues running even if an uncaught exception occurs, allowing us to log and address the issue without interrupting service.

maryam4s26 avatar Aug 20 '24 15:08 maryam4s26

https://nodejs.org/api/process.html#warning-using-uncaughtexception-correctly

andersevenrud avatar Aug 20 '24 15:08 andersevenrud

If you provide stack traces for these cases then I'll happily fix that if they come from the OS.js core.

andersevenrud avatar Aug 20 '24 16:08 andersevenrud

If you provide stack traces for these cases then I'll happily fix that if they come from the OS.js core.

Unfortunately, I did not understand what you meant.

maryam4s26 avatar Aug 20 '24 16:08 maryam4s26

If you experience crashes from uncaught exceptions, then you can open an issue and paste the stack trace from the crash there so I can look at it.

Having a global exception handler like you describe with uncaughtException is generally considered bad practice and I want to avoid having this in the codebase.

It's much better to fix the actual exceptions. But this will require stack traces and/or instructions on how to reproduce.

andersevenrud avatar Aug 20 '24 16:08 andersevenrud

You are right. I haven't run into osjs directly yet. But I was developing an app based on OSJS, and I did the following in one of its APIs.

      route('POST', `/${appName}/download`, async (req, res) => {
        try {
        } catch (err) {
          console.log(err);
          res
            .status(err?.code || 500)
            .send(err);
        }
      });

A part of the code caused the code to be caught, But the code value in my error was not a number and osjs crashed because it could not assign string value to status. The best solution is that I upgrade the catch code so that I don't get into trouble as below:

         console.log(err);
          if (typeof err?.code === 'number') {
            res.status(err.code).send(err);
            return;
          }
          res
            .status(err?.response?.status || 500)
            .send(err);

But the use of breaking the code below is a solution in general.

 process.on('uncaughtException', (error) => {
  console.log(error);
});

maryam4s26 avatar Aug 20 '24 16:08 maryam4s26