是否可以在电子主过程中捕获渲染器过程的异常? [英] Is it possible to catch exceptions of renderer processes in electrons main process?

查看:116
本文介绍了是否可以在电子主过程中捕获渲染器过程的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Electrons Quick Start Projekt (提交dbef48ee7d072a38724ecfa57601e39d36e9714e)来测试异常。

I'm using Electrons Quick Start Projekt (Commit dbef48ee7d072a38724ecfa57601e39d36e9714e) to test exceptions.

index.html 中,我从 renderer.js更改了所需模块的名称 rendererXXX.js

require('./renderer.js')

这会产生预期的Exeption(在该窗口的devtools):

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?

EDIT:

我还包装了将 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');
});

这篇关于是否可以在电子主过程中捕获渲染器过程的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆