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

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

问题描述

我正在使用 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');
});

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

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