Electron中的自定义错误窗口/处理

6
我目前正在构建一个文件备份应用程序,需要进行大量的文件系统读写操作。大部分工作都很顺利,但我在应用程序的错误处理方面遇到了一些困难。
在下面的截图中,最后一个路径不是有效的目录,并返回异常,如您所见。

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 :) 

我的问题是,是否可以用自己的错误窗口替换标准错误窗口?或者在某些情况下忽略错误窗口的弹出?第一次使用Electron,如果这个问题很明显,请原谅。
谢谢!
1个回答

16
当您从readdir中抛出错误时,它会被顶层的uncaughtException处理程序捕获,第一行指示了这一点:“未捕获异常”。 您需要做的是在主进程中为uncaughtException添加自己的自定义处理程序,并从那里显示任何对话框。 请查看对话框模块。 例如,您可以使用dialog.showMessageBox方法配置有关错误对话框的各种设置,如下所示:
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);
});

1
不幸的是,这对于像require语句这样的代码部分不起作用。 - m4heshd
@m4heshd 只是在所有顶级导入之前挂钩uncaughtException事件的问题吗?(尽管看起来很奇怪) - pushkin
出于某种原因,这仍然会发生。自从 Electron v3 或者之后,我已经尝试了几乎所有的方法。但是最终还是放弃了。 - m4heshd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接