0

在 Electron 中,如果我在后端的任何地方抛出错误,它会转到自定义窗口。试图找到一种方法来捕捉它以推送到我的应用程序中的自定义区域,我发现我可以使用process.on('uncaughtException'). 但是,我一直在尝试运行发件人来发送错误或报告。我试过的:

ipcMain.on('main', async (e, data) => {
  try {
    await someModule(data)
    process.on('uncaughtException', err => e.sender.send('error', err.message))
    return e.sender.send('audit', 'No issues found')
  } catch (err) {
    console.log(err)
  }
})

模块.js:

module.export = data => {
  throw Error('this is a test')
}

在上面,我将两者都发送and到渲染器。我已经研究了一种将 'uncaughtException' 传递给三元组的方法,但我找不到任何关于如何为 'uncaughtException' 设置条件的文档,但我确实尝试了:

process.on('uncaughtException', err => {
  if (err) return e.sender.send('error', err.message)
  return e.sender.send('audit', 'test complete')
})

以上仅在存在错误时才有效,研究:

在 Electron 中,如何拦截错误以将其从 main 传递给渲染器而不抛出默认错误窗口?

4

1 回答 1

0

如果您使用ipcMain.handle,您将能够像这样处理渲染器过程中的错误

// Main process
ipcMain.handle('my-invokable-ipc', async (event, data) => {
  await someModule(data)
  return 'No issues found'
})

// Renderer process
async () => {
  try {
    const result = await ipcRenderer.invoke('my-invokable-ipc', data)
    console.log(result) // 'No issues found' if someModule did not throw an error
  } catch (err) {
    // you can handle someModule errors here
  }
}

更新:这种方法的一个问题是,发送到渲染器进程的错误是序列化的,即使它是用 try/catch 处理的,它也会被打印出来。

要解决此问题,您还可以处理主进程中的错误

// Main process
ipcMain.handle('my-invokable-ipc', async (event, data) => {
  try {
    await someModule(data)
    return 'No issues found'
  } catch (err) {
    // handle someModule errors and notify renderer process
    // return err.message or any other way you see fit
  }
})

// Renderer process
async () => {
  const result = await ipcRenderer.invoke('my-invokable-ipc', data)
  console.log(result) // 'No issues found' if someModule did not throw an error
}
于 2021-02-24T07:53:56.950 回答