crashReporter
Envía los informes de fallos a un servidor remoto.
[!IMPORTANT] If you want to call this API from a renderer process with context isolation enabled, place the API call in your preload script and expose it using the
contextBridgeAPI.
El siguiente es un ejemplo de como configurar Electron para que envié automáticamente reportes de error a un servidor remoto:
const { crashReporter } = require('electron')
crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' })
For a guide to collecting, receiving and symbolicating crash reports, including how to run your own crash server or use a hosted service, see the Crash Reporting tutorial.
Electron uses Crashpad to monitor and report crashes. Crashpad uses the same upload protocol as Breakpad, so servers that accept Breakpad minidumps can receive Electron's crash reports.
Crash reports are stored under the directory returned by app.getPath('crashDumps'). You can override it by calling app.setPath('crashDumps', '/path/to/crashes') before starting the crash reporter. The layout of files inside this directory is an implementation detail and may change between versions of Electron.
The crashReporter module is disabled in Mac App Store builds. Its methods can be called, but they do nothing: no crash reports are collected or uploaded, getUploadedReports() returns an empty array and getUploadToServer() returns false.
On Windows, some crashes never reach an in-process crash handler, most notably __fastfail terminations (STATUS_STACK_BUFFER_OVERRUN, raised by security-check failures, Control Flow Guard violations and the C runtime's abort()). To capture these, Electron ships electron_wer.dll, a Windows Error Reporting (WER) runtime exception helper that Windows (10 20H1 and later) loads out-of-process after such a crash and that asks the crashpad handler to write a minidump. When crashReporter.start() is called, Electron lists the DLL under HKEY_CURRENT_USER\Software\Microsoft\Windows\Windows Error Reporting\RuntimeExceptionHelperModules, which Windows requires before it will load a helper, and registers it for every Electron process. The helper is looked up as <executable name>_wer.dll next to the executable, so if you rename electron.exe to myapp.exe when packaging, rename electron_wer.dll to myapp_wer.dll as well. Installers that write to HKEY_LOCAL_MACHINE may list it there instead. To opt out, do not ship the DLL.
Métodos
El módulo crashReporter tiene los siguientes métodos:
crashReporter.start(options)
History
| Version(s) | Changes |
|---|---|
None | Opciones |
None | Invocación obsoleta de este método en el proceso renderizador. |
None | Valor por defecto de la opción |
None | El parámetro |
Este método debe ser llamada antes de usar cualquier otra APIs crashReporter. Una vez inicializado de esta manera, el crashpad handler recopila los fallos desde todos los procesos creados posteriormente. El crash reporter no puede ser desactiva una vez iniciado.
Este método debería ser llamado tan pronto como sea posible al iniciar la aplicación, preferentemente antes de app.on('ready'). Si el crash reporter no está iniciado al tiempo que un renderer process este creado, entonces ese renderer process no será monitoreado por el crash reporter.
[!Nota: Puedes probar el informe del cuelgue generando un cuelgue usando
process.crash().
[!NOTA] Si necesitas enviar parámetros
extraadicionales/actualizados tras tu primera invocaciónstartpuedes invocar aaddExtraParameter.
[!NOTA] Los parámetros pasados en
extra,globalExtrao establecidos conaddExtraParametertienen límites en la longitud de las claves y los valores. Key names must be at most 39 bytes long, and values must be no longer than 20320 bytes. Keys with names longer than the maximum are ignored, and a warning is emitted. Values longer than the maximum length are truncated.
[!NOTA] Este método solo está disponible en el proceso principal.
crashReporter.getLastCrashReport()
History
| Version(s) | Changes |
|---|---|
None | Llamar a este método en el proceso de renderización. |
Returns CrashReport | null - The date and ID of the crash report with the most recent upload time, from the list returned by getUploadedReports(). If there are no crash reports at all, null is returned.
If no report has been uploaded yet but some are stored on disk, a report that has not been uploaded may be returned. Check that its id is not empty before treating it as uploaded.
[!NOTA] Este método solo está disponible en el proceso principal.
crashReporter.getUploadedReports()
History
| Version(s) | Changes |
|---|---|
None | Llamar a este método en el proceso de renderización. |
Devuelve CrashReport[]:
Returns the crash reports stored on disk. Each report contains the date it was uploaded and the ID that the crash server returned for it.
Despite the method's name, reports that have not been uploaded (for example because uploadToServer is false, the upload failed, or the report was rate limited) are included too. For those reports, id is an empty string and date is not meaningful. To list only uploaded reports, filter out reports with an empty id.
[!NOTA] Este método solo está disponible en el proceso principal.
crashReporter.getUploadToServer()
History
| Version(s) | Changes |
|---|---|
None | Llamar a este método en el proceso de renderización. |
Devuelve boolean - Si los informes serían enviados al servidor. Establecer a través del método start o setUploadToServer.
[!NOTA] Este método solo está disponible en el proceso principal.
crashReporter.setUploadToServer(uploadToServer)
History
| Version(s) | Changes |
|---|---|
None | Llamar a este método en el proceso de renderización. |
uploadToServerboolean - Si los reportes deben enviarse o no al servidor.
Esto normalmente sería controlado por las preferencias del usuario. Esto no tiene efecto si invocó antes de invocar start.
[!NOTA] Este método solo está disponible en el proceso principal.
crashReporter.addExtraParameter(clave, valor)
keystring - La clave del parámetro, debe tener menos de 39 bytes.keystring - La clave del parámetro, debe tener menos de 20320 bytes.
Establecer un parámetro adicional que se enviará con el informe de fallos. Los valores especificados aquí serán enviados, adicionalmente cualquier valor establecidos a través de la opción extra cuando fue llamado start. Calling this again with the same key replaces the value. The value is read when a crash happens, so you can update it as your app's state changes.
Los parámetros agregados de esta manera (o a través del parámetro extra al crashReporter.start) son específicos del proceso de llamada. Agregar parámetros extras en el main process no causarán que esos parámetros sean enviado junto con los fallos del renderer u otros procesos hijos. De manera similar, agregar parámetros extras en un renderer process no dará como resultado que esos parámetros sean enviados con los fallos que ocurren en otros renderer processes o en el main process. Processes created with utilityProcess have no API for setting extra parameters, so only globalExtra values are sent with their crashes.
[!NOTA] Los parámetros tienen límites de longitud de llaves y valores. Los nombres de llave no deben ser más largos que 39 bytes, y los valores deben ser no más largos que 20320 bytes. Keys with names longer than the maximum are ignored, and a warning is emitted. Values longer than the maximum length are truncated.
crashReporter.removeExtraParameter(key)
keystring - La clave del parámetro, debe tener menos de 39 bytes.
Elimina un parámetro adicional del conjunto actual de parámetros. Los cuelgues futuros no incluirán este parámetro.
crashReporter.getParameters()
Returns Record<string, string> - The current 'extra' parameters of the crash reporter in the calling process, as set with the extra option and addExtraParameter. Parameters set with the globalExtra option are not included.
En los procesos heredados de Nodo
Since require('electron') is not available in Node child processes (processes run with ELECTRON_RUN_AS_NODE, such as those created with child_process.fork()), the following APIs are available on the process object in Node child processes.
If the crash reporter is started in the main process, Node child processes are monitored automatically. There is no way to start the crash reporter from a Node child process.
process.crashReporter.getParameters()
Consulte crashReporter.getParameters().
process.crashReporter.addExtraParameter(key, value)
Consulte crashReporter.addExtraParameter(key, value).
process.crashReporter.removeExtraParameter(key)
Consulte crashReporter.removeExtraParameter(key).
Carga útil del informe de fallos
El informador de fallos enviará la siguiente información al submitURL como un multipart/form-data POST. Unless compress is false, the request body is gzip-compressed and sent with Content-Encoding: gzip.
verstring - La versión de Electron.platformstring - por ejemplo, "win32".process_typestring - e.g. 'renderer', or 'browser' for the main process.guidstring - por ejemplo, "5e1286fc-da97-479e-918b-6bfb0c3d1c72"._versionstring - La versión enpackage.json._productNamestring - El nombre del producto en el objetocrashReporteroptions.prodstring - Nombre del producto subyacente. En esta caso Electron._companyNamestring - El nombre de la empresa en el objetocrashReporteroptions. Only sent if the deprecatedcompanyNameoption is set.upload_file_minidumpArchivo - El informe de fallos en el formato deminidump.- Todas las propiedades de nivel uno del objeto
globalExtraen el objetocrashReporteroptions. - All extra parameters of the process that crashed, set with the
extraoption (main process only) oraddExtraParameter.
Crashpad and Chromium may add other fields to the upload. These are not part of Electron's API and can change without notice, so don't rely on them.
The body of the server's response is stored as the crash report's ID, and is returned in the id field by getUploadedReports().