我正在使用 Electrons Quick Start Projekt (提交 dbef48ee7d072a38724ecfa57601e39d36e9714e)以测试异常。
在 index.html
中,我将所需模块的名称从 renderer.js
更改为 rendererXXX.js
。
require('./renderer.js')
这会导致预期的异常(在该窗口的开发工具中可见):
Uncaught Error: Cannot find module './rendererXXX.js'
现在,如果主进程(参见 main.js
)知道一个渲染器进程失败,那就太好了。因此,我将窗口的实例化 package 到一个 try-catch-block 中
try {
app.on('ready', createWindow)
} catch (e) {
console.log("Exception caught: " + e.message);
} finally {
// nothing yet
}
但我意识到,异常没有转发到主进程。那么处理渲染器进程异常的典型方法是什么 - 有没有办法从主进程处理它们?
编辑:
我也将加载 index.html
的行 package 到 try-catch 中,但我仍然无法处理错误:
try {
// and load the index.html of the app.
mainWindow.loadURL(`file://${__dirname}/index.html`)
} catch (e) {
console.log("Exception caught in 'createWindow': " + e.message);
}
最佳答案
Electron 窗口在它们自己的进程中呈现。因此,主进程和渲染进程之间几乎没有通信。您能做的最好的事情就是捕获渲染过程中的错误并使用 Electrons IPC 模块将它们传回您的主进程。
在你的渲染过程中:
var ipc = require('electron').ipcRenderer;
window.onerror = function(error, url, line) {
ipc.send('errorInWindow', error);
};
在你的主进程中:
var ipc = require('electron').ipcMain;
ipc.on('errorInWindow', function(event, data){
console.log(data)
});
此外,您的主进程可以直接在窗口(或在 Windows webContents
)上监视一组有限的事件:
window.on('unresponsive', function() {
console.log('window crashed');
});
...
window.webContents.on('did-fail-load', function() {
console.log('window failed load');
});
关于javascript - 是否有可能在 Electron 主进程中捕获渲染进程的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39249886/