問題描述
我正在使用 Electrons 快速入門項目(提交 dbef48ee7d072a38724ecfa57601e39d36e9714e)來測試異常.
I'm using Electrons Quick Start Projekt (Commit dbef48ee7d072a38724ecfa57601e39d36e9714e) to test exceptions.
在 index.html
中,我將所需模塊的名稱從 renderer.js
更改為 rendererXXX.js
.
In index.html
I changed the name of the required module from renderer.js
to rendererXXX.js
.
require('./renderer.js')
這會導致預期的異常(在該窗口的開發工具中可見):
which results in an expected Exeption (it is visible in the devtools for that window):
Uncaught Error: Cannot find module './rendererXXX.js'
現在,如果主進程(參見 main.js
)知道一個渲染器進程失敗,那就太好了.因此,我將窗口的實例化包裝到 try-catch-block 中
Now it would be nice if the main-process (see main.js
) is aware that one renderer process failed. Thus I wrapped the instatiation of the window into a try-catch-block
try {
app.on('ready', createWindow)
} catch (e) {
console.log("Exception caught: " + e.message);
} finally {
// nothing yet
}
但我意識到,異常沒有轉發到主進程.那么處理渲染器進程異常的典型方法是什么 - 有沒有辦法從主進程處理它們?
But I realized, that the Exception is not forwarded to the main-process. So what are typical ways to handle exceptions of renderer processes - is there a way to handle them from the main-process?
我還將加載 index.html
的行包裹到 try-catch 中,但我仍然無法處理錯誤:
I also wrapped the line that loads the index.html
into try-catch, but still I can't handle the error:
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);
}
推薦答案
電子窗口在自己的進程中渲染.因此,主進程和渲染進程之間幾乎沒有通信.您能做的最好的事情就是在渲染過程中捕獲錯誤并使用 Electrons IPC 模塊將它們傳遞回您的主進程.
Electron windows are rendered in their own process. Because of this there is little if any communication between main process and render processes. The best you can do is catch errors in the render process and use Electrons IPC module to pass them back to your main process.
在你的渲染過程中:
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)
});
此外,您的主進程可以直接在窗口(或窗口 webContents
)上觀察一組有限的事件:
Additionally your main process can watch for a limited set of events directly on the window (or on the windows webContents
):
window.on('unresponsive', function() {
console.log('window crashed');
});
...
window.webContents.on('did-fail-load', function() {
console.log('window failed load');
});
這篇關于是否可以在電子主進程中捕獲渲染器進程的異常?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!