Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom error window/handling in Electron

I'm currently building an application for file backup, and it got quite a bit of reading and writing to the filesystem. Most of it works great, but I'm struggling a bit with the error handling of the app.

In the screenshot below the last path is not a valid directory and return an exception as you can see.

enter image description here

function getTotalSize(pathToDir, dir) {
fs.readdir(pathToDir, function(err, files) {
    if (err) {
        // handle my error here
        throw new Error('something bad happened');
        return;
    }

    // continue if no errors :) 

My question is, is it possible to replace the standard error window with my own? Or in some cases ignore the pop up of the error window? First time working with Electron so sorry if this is an obvious one.

Thanks!

like image 784
Sander Hellesø Avatar asked Dec 10 '22 06:12

Sander Hellesø


1 Answers

When you throw the error from readdir it gets caught by the top-level uncaughtException handler, indicated by the the first line: "Uncaught Exception".

What you need to do is add your own custom handler for the uncaughtException in your main process and show whatever dialog you want from there.

Take a look at the dialog module.

As an example, you can use the dialog.showMessageBox method to configure all sorts of things about the error dialog like this:

process.on("uncaughtException", (err) => {
   const messageBoxOptions = {
        type: "error",
        title: "Error in Main process",
        message: "Something failed"
    };
    dialog.showMessageBoxSync(messageBoxOptions);

    // I believe it used to be the case that doing a "throw err;" here would
    // terminate the process, but now it appears that you have to use's Electron's
    // app module to exit (process.exit(1) seems to not terminate the process)
    app.exit(1);
});
like image 200
pushkin Avatar answered Dec 12 '22 18:12

pushkin