Saltar al contenido principal

crashReporter

Envía los informes de fallos a un servidor remoto.

ProcessMainRenderer

[!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 contextBridge API.

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 rateLimit y compress añadidas.

None

Invocación obsoleta de este método en el proceso renderizador.

None

Valor por defecto de la opción compress cambiada desde false a true.

None

El parámetro submitURL ahora es opcional cuando uploadToServer sea false.

  • options Object
    • submitURL string (opcional) - URL a la que serán enviados los reportes de fallos como POST. Requerido a menos que uploadToServer sea false.
    • productName string (opcional) - Por defecto app.name.
    • companyName string (opcional) Deprecated - Alias obsoleto para { globalExtra: { _companyName: ... } }.
    • uploadToServer boolean (octional) - Si los reportes de fallos deberían ser enviados a un servidor. Si es false, los reportes de fallos serán recolectados y almacenados en un directorio de fallas, pero no serán subidos. Por defecto es true.
    • ignoreSystemCrashHandler boolean (optional) macOS Linux - If true, crashes generated in the main process will not be forwarded to the system crash handler. This option has no effect on Windows. Por defecto es false.
    • rateLimit boolean (optional) - If true, limit the number of crashes uploaded to 1/hour. Crash reports over the limit are not uploaded, but are still stored on disk. Por defecto es false.
    • compress boolean (opcional) - Si es true, los reportes de fallos serán comprimidos y subidos con Content-Encoding: gzip. Setting this to false while uploadToServer is true is deprecated and logs a deprecation warning. Por defecto es true.
    • extra Record<string, string> (opcional) - Cadena adicional de anotaciones clave/valor que serán enviadas junto con informes de cuelgue que sean generados en el proceso principal. Sólo se admiten valores de cadena. Cuelgue generado en procesos heredados no incluirán estos parámetros adicionales. Para añadir parámetros adicionales para informes de cuelgue generados desde procesos heredados, invoque addExtraParameter desde el proceso heredado.
    • globalExtra Record<String, String> (opcional) - Extra string con anotaciones clave/valor que serán enviados junto con los reportes de fallos generados en cualquier proceso. Estas anotaciones no pueden ser cambiadas una vez que el crash reporter ha sido iniciado. Si una clave esta presente en los parámetros global extra y en los parámetros extra process-specific, entonces el parámetro global tomará precedencia. Por defecto, productName y la versión de la aplicación son incluidas, así como la versión de Electron. Global extra parameters are not returned by getParameters().

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 extra adicionales/actualizados tras tu primera invocación start puedes invocar a addExtraParameter.

[!NOTA] Los parámetros pasados en extra, globalExtra o establecidos con addExtraParameter tienen 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

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

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

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
  • uploadToServer boolean - 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)​

  • key string - La clave del parámetro, debe tener menos de 39 bytes.
  • key string - 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)​

  • key string - 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.

  • ver string - La versión de Electron.
  • platform string - por ejemplo, "win32".
  • process_type string - e.g. 'renderer', or 'browser' for the main process.
  • guid string - por ejemplo, "5e1286fc-da97-479e-918b-6bfb0c3d1c72".
  • _version string - La versión en package.json.
  • _productName string - El nombre del producto en el objeto crashReporter options.
  • prod string - Nombre del producto subyacente. En esta caso Electron.
  • _companyName string - El nombre de la empresa en el objeto crashReporter options. Only sent if the deprecated companyName option is set.
  • upload_file_minidump Archivo - El informe de fallos en el formato de minidump.
  • Todas las propiedades de nivel uno del objeto globalExtra en el objeto crashReporter options.
  • All extra parameters of the process that crashed, set with the extra option (main process only) or addExtraParameter.

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().