javascriptnode.jserror-handlingelectron

Electron - Is there a way to run code after throwing an error?


I'm making my first electron app, and I'm trying to implement error handling. If I write:

throw new Error('something happened')

A large, convenient error alert modal appears. I'd like to use this and also call app.quit() afterwards to close the app. Of course, calling throw terminates the function, and there's no promise or anything for the modal alert.

Is there a way to make a call to app.quit() after the user clicks "OK" on the error alert?


Solution

  • This is the built in electron error handling which kicks in for errors that you did not handle properly. I do not know if you can piggyback their error handling and add additional logic to it, but I would highly discourage it, because it catches errors on the highest level and breaks whatever happened in your business logic.

    What you'll want to do is to handle the error properly yourself and then show a Messagebox: Electron - Messagebox.

    A Messagebox does return a promise with which you can achieve what you are trying to.

    Some example code could look like this:

    const { dialog } = require('electron')
    
    const functionThatMighFail = () => {
        throw new Error('something happened');
    }
    
    const main = () => {
        try {
            functionThatMightFail();
         } catch (error: Error) {
            const options = {
                type: 'error',
                buttons: ['OK'],
                title: 'Error',
                message: 'Something went wrong!',
                detail: error.message,
            };
    
            dialog
                .showMessageBox(null, options)
                .then(() => app.quit());
        }
    }
    

    You also might want to consider checking a bit deeper into how to handle errors in applications properly and whether it is possible to continue after an error. I think it would pose bad user experience to simply close an app when an error happens, but I wrote the answer in such a way that it matches your question.