Skip to main content

Electron CrashSight Integration Guide

This guide will help you integrate the crashsight-electron plugin into your Electron project to enable crash reporting functionality.

Prerequisites

  • Node.js environment (recommended 16.x or higher)
  • Electron project already created
  • Windows development environment (requires Visual Studio or Windows Build Tools for compiling native modules)

Step 1: Install the Plugin

1.1 Copy Plugin Directory

Copy the crashsight-electron directory to your Electron project root directory.

your-electron-project/
├── main.js
├── package.json
├── crashsight-electron/ ← Copy here
│ ├── libs/
│ │ └── CrashSight64.dll
│ ├── src/
│ ├── package.json
│ └── ...
└── ...

1.2 Install Dependencies

Add the dependency to your project root package.json:

{
"dependencies": {
"crashsight-electron": "file:./crashsight-electron"
}
}

Then run:

npm install

Note: The native module will be automatically compiled during installation. If compilation fails, ensure you have installed:

  • Windows: Visual Studio 2019/2022 or Windows Build Tools
  • Build tools will be installed automatically, the first installation may take a long time

Version Compatibility:

  • This plugin uses N-API (Node-API), providing excellent cross-version compatibility
  • The following Electron versions have been tested and passed (100% pass rate):
    • ✅ Electron 16.2.0 (Node.js 16.14.2)
    • ✅ Electron 18.3.0 (Node.js 16.14.2)
    • ✅ Electron 20.3.0 (Node.js 16.15.0)
    • ✅ Electron 22.3.0 (Node.js 18.15.0)
    • ✅ Electron 27.3.0 (Node.js 18.17.1)
  • Theoretically supports Electron 16+ and Node.js 16+
  • If you encounter module loading errors, run npx electron-rebuild to recompile

Step 2: Configure Build Options

2.1 Configure electron-builder

Add or modify the build configuration in your project root package.json:

{
"build": {
"files": [
"main.js",
"index.html",
"crashsight-electron/**/*",
"!crashsight-electron/**/*.{md,ts,map}",
"node_modules/**/*",
"!node_modules/**/*.{md,ts,map}",
"!**/*.{md,ts,map}"
],
"asarUnpack": [
"crashsight-electron/libs/**/*",
"crashsight-electron/build/**/*"
]
}
}

Important Notes:

  • The asarUnpack configuration is required to extract DLL and native modules from the asar package
  • These files must be extracted to be loaded by the system

Step 3: Initialize CrashSight

3.1 Import Module in Main Process

Import CrashSight in your main process file (usually main.js):

const { app, BrowserWindow } = require('electron');
const { CrashSightAgent, CrashSightLogLevel } = require('crashsight-electron');
const path = require('path');

3.2 Initialize Configuration

Initialize CrashSight in app.whenReady(). Must be initialized before creating windows:

let crashSight = null;

function initCrashSight() {
try {
crashSight = new CrashSightAgent();

// 1. Configure debug mode (optional, recommended for development)
crashSight.configDebugMode(true); // Set to false for production

// 2. Configure server URL (required)
crashSight.configCrashServerUrl('pc.crashsight.qq.com');

// 3. Configure log level (optional)
crashSight.configCrashReporter(CrashSightLogLevel.CSLogLevelInfo);

// 4. Set app version (recommended)
crashSight.setAppVersion(app.getVersion());

// 5. Set user ID (optional, for user identification)
crashSight.setUserId('your-user-id');

// 6. Set log path (optional, for storing CrashSight logs)
crashSight.setLogPath(path.join(app.getPath('userData'), 'crashsight-logs'));

// 7. Enable VEH (optional, Windows platform)
crashSight.setVehEnable(true);

// 8. Initialize (will automatically register exception handlers)
crashSight.initWithAppId('your-app-id');

} catch (error) {
console.error('Failed to initialize CrashSight:', error);
// Application should continue running even if CrashSight initialization fails
}
}

app.whenReady().then(() => {
// Initialize CrashSight first
initCrashSight();

// Then create window
createWindow();
});

3.3 Configuration Parameters

MethodDescriptionRequiredCall Timing
configDebugMode(enable)Enable/disable debug modeOptionalBefore initialization
configCrashServerUrl(url)Set crash reporting server URLRequiredBefore initialization
configCrashReporter(level)Set log levelOptionalBefore initialization
setAppVersion(version)Set application versionRecommendedBefore initialization
setUserId(userId)Set user IDOptionalBefore/after initialization
setLogPath(path)Set log storage pathOptionalBefore initialization
setVehEnable(enable)Enable VEH (Windows)OptionalBefore initialization
initWithAppId(appId)Initialize with AppIdRequiredCall last

Important Notes:

  • initWithAppId() will automatically register exception handlers for the main process, capturing uncaught exceptions and unhandled Promise rejections
  • All configuration methods (except setUserId) must be called before initWithAppId()
  • If initialization fails, the application will continue running, but crash reporting will be unavailable

Step 4: Get AppId

  1. Log in to the CrashSight console
  2. Create an application or select an existing one
  3. Get the AppId from application settings
  4. Replace 'your-app-id' in the code with your AppId

Step 5: Testing and Verification

5.1 Development Environment Testing

Run the application:

npm start

5.2 Test Exception Capture

CrashSight will automatically capture the following exceptions:

  1. Main process uncaught exceptions: Throw exceptions directly in the main process
  2. Main process unhandled Promise rejections: Trigger unhandled Promise rejections in the main process

5.3 Build Testing

Build the application:

npm run build:win

The built application is located in the dist/win-unpacked/ directory. Run the built application to verify functionality.

Step 6: Advanced Configuration (Optional)

6.1 Custom DLL Path

If your DLL file is not in the default location, you can specify the path:

const crashSight = new CrashSightAgent({
libPath: 'C:\\path\\to\\CrashSight64.dll'
});

6.2 Set Workspace

crashSight.setWorkSpaceW('D:\\workspace');

6.3 Manually Report Exceptions

crashSight.reportException(
4, // Exception type
'ErrorName', // Exception name
'Error message', // Exception message
'Stack trace...', // Stack trace
JSON.stringify({extra: 'data'}), // Extra information (JSON string)
false, // Whether to report asynchronously (false means synchronous)
'' // Attachment path (optional)
);

6.4 Set User Custom Values

// Set integer type
crashSight.setUserValue('level', 10);

// Set string type
crashSight.setUserValue('username', 'user123');

// Set string array type
crashSight.setUserValue('tags', ['tag1', 'tag2', 'tag3']);

Step 7: Complete API Reference

7.1 Initialization APIs

initWithAppId(appId)

Initialize CrashSight SDK.

Parameters:

  • appId (string, required): APPID of registered project

Notes:

  • Initialize as early as possible to enable crash detection and reporting features
  • Automatically registers exception handlers for the main process, capturing uncaught exceptions and unhandled Promise rejections
  • Must be called after all configuration methods

Example:

crashSight.initWithAppId('your-app-id');

7.2 Configuration APIs

configDebugMode(enable)

Set debug mode.

Parameters:

  • enable (boolean): Whether to enable debug mode

Notes:

  • Disabled by default
  • Must be called before initWithAppId()
  • When enabled, more logs will be printed to facilitate problem location

Example:

crashSight.configDebugMode(true);  // Development
crashSight.configDebugMode(false); // Production

configCrashServerUrl(url)

Set crash reporting server URL.

Parameters:

  • url (string, required): Target domain name, e.g., 'pc.crashsight.qq.com'

Notes:

  • Must be called before initWithAppId()

Example:

crashSight.configCrashServerUrl('pc.crashsight.qq.com');

configCrashReporter(level)

Set custom log reporting level.

Parameters:

  • level (number): Log level
    • 0: Off
    • 1: Error
    • 2: Warn
    • 3: Info (default)
    • 4: Debug

Notes:

  • Must be called before initWithAppId()
  • Can use CrashSightLogLevel enum values

Example:

crashSight.configCrashReporter(CrashSightLogLevel.CSLogLevelInfo);

setAppVersion(version)

Set application version.

Parameters:

  • version (string): Version number string

Notes:

  • Must be called before initWithAppId()

Example:

crashSight.setAppVersion('1.0.0');

setUserId(userId)

Set user ID.

Parameters:

  • userId (string): User identifier

Notes:

  • User ID defaults to "unknown"
  • Can be called before or after initialization

Example:

crashSight.setUserId('user123');

setDeviceId(deviceId)

Set device ID.

Parameters:

  • deviceId (string): Device unique identifier

Notes:

  • Default uses UUID as device ID
  • Must be called before initWithAppId()

Example:

crashSight.setDeviceId('device-uuid-123');

setLogPath(path)

Set upload path for log after crash.

Parameters:

  • path (string): Absolute path for log files

Notes:

  • Read permission is required
  • Must be called before initWithAppId()
  • Does not support GBK character paths (use setLogPathW if needed)

Example:

crashSight.setLogPath('C:\\logs\\crashsight');

setLogPathW(path)

Set upload path for log after crash (wide char version, supports GBK characters).

Parameters:

  • path (string): Absolute path for log files (supports Chinese and other GBK characters)

Notes:

  • Read permission is required
  • Must be called before initWithAppId()
  • Windows platform only

Example:

crashSight.setLogPathW('D:\\中文路径\\logs');

setEnvironmentName(serverEnv)

Set distribution channel.

Parameters:

  • serverEnv (string): Distribution channel name

Notes:

  • Each network connection or report can carry this field to collect statistics for different distribution channels

Example:

crashSight.setEnvironmentName('production');

7.3 Exception Reporting APIs

reportException(type, name, reason, stackTrace, extras, isAsync, errorAttachPath?)

Actively report errors.

Parameters:

  • type (number, required): Exception type
    • 0-3: Internal reserved types, invalid if passed in
    • 4: C# exception
    • 5: JavaScript exception
    • 6: Lua exception
  • name (string, required): Exception name, cannot be null
  • reason (string, required): Exception reason, cannot be null
  • stackTrace (string, required): Stack trace, cannot be null
  • extras (string): Extra information (JSON string)
  • isAsync (boolean): Whether to report asynchronously (Win/Xbox only)
    • true: Asynchronous reporting (default)
    • false: Synchronous reporting (blocks until reporting completes)
  • errorAttachPath (string, optional): Absolute path of attachment (GBK characters not supported, Win/Xbox valid)

Notes:

  • Can be called manually when an error is caught or needs to be reported
  • Supports multi-threaded calls
  • If isAsync is false, will synchronously wait for reporting to complete, suitable for reporting before application exit

Example:

crashSight.reportException(
5, // JavaScript exception
'TypeError',
'Cannot read property of undefined',
'at Object.<anonymous> (file.js:10:5)\n...',
JSON.stringify({ userId: '123', level: 10 }),
false, // Synchronous reporting
'' // No attachment
);

reportExceptionW(type, name, reason, stackTrace, extras, isAsync, errorAttachPath?)

Actively report errors (wide char version, supports GBK character paths).

Parameters:

  • type (number, required): Exception type (same as reportException)
  • name (string, required): Exception name
  • reason (string, required): Exception reason
  • stackTrace (string, required): Stack trace
  • extras (string): Extra information (JSON string)
  • isAsync (boolean): Whether to report asynchronously
  • errorAttachPath (string, optional): Log attachment path (wide char, supports GBK characters, Windows only)

Notes:

  • Same functionality as reportException, but supports attachment paths with GBK characters
  • Windows platform only

Example:

crashSight.reportExceptionW(
5,
'TypeError',
'Error message',
'Stack trace...',
'',
false,
'D:\\中文路径\\attachment.log'
);

7.4 User Custom Data APIs

addSceneData(key, value)

Add custom data (Key-Value).

Parameters:

  • key (string): Key name
  • value (string): Value (string type)

Notes:

  • Set user-defined Key-Value data, will be reported together with exception info when sending crash
  • View page: Crash Details -> Download Attachments -> valueMapOthers.txt

Example:

crashSight.addSceneData('level', '10');
crashSight.addSceneData('scene', 'battle');

setUserValue(key, value)

Set user custom values (supports multiple types).

Parameters:

  • key (string): Key name
  • value (number | string | string[]): Value
    • number: Integer type
    • string: String type
    • string[]: String array type

Notes:

  • Internally calls addSceneData, automatically adds type prefix
  • Integer type uses I# prefix
  • String type uses K# prefix
  • String array type uses S# prefix

Example:

// Integer type
crashSight.setUserValue('level', 10);

// String type
crashSight.setUserValue('username', 'user123');

// String array type
crashSight.setUserValue('tags', ['tag1', 'tag2', 'tag3']);

7.5 Windows Platform Specific APIs

setVehEnable(enable)

Set VEH (Vectored Exception Handling) capture switch.

Parameters:

  • enable (boolean): Whether to enable VEH

Notes:

  • Win/Xbox platform only
  • Must be called before initWithAppId()
  • VEH can capture more types of crashes

Example:

crashSight.setVehEnable(true);

reportCrash()

Actively report crash information.

Notes:

  • Win/Xbox platform only
  • Manually trigger crash reporting

Example:

crashSight.reportCrash();

reportDump(dumpPath, isAsync)

Actively report dump file.

Parameters:

  • dumpPath (string): Dump file directory
  • isAsync (boolean): Whether to report asynchronously

Notes:

  • Win/Xbox platform only

Example:

crashSight.reportDump('C:\\dumps', true);

setCrashCallback(callback)

Set crash callback.

Parameters:

  • callback (Function): Crash callback function
    • Function signature: (type: number, guid: string) => void
    • type: Crash type
    • guid: Issue GUID

Notes:

  • Win/Xbox platform only
  • Callback is called when a crash occurs, return value will be included in crash report

Example:

crashSight.setCrashCallback((type, guid) => {
console.log(`Crash occurred: type=${type}, guid=${guid}`);
});

setExtraHandler(enable)

Set extra exception capture switch.

Parameters:

  • enable (boolean): Whether to enable extra exception handling

Notes:

  • Win/Xbox platform only

Example:

crashSight.setExtraHandler(true);

uploadGivenPathDump(dumpDir, isExtraCheck)

Upload dump file from given path.

Parameters:

  • dumpDir (string): Dump file directory
  • isExtraCheck (boolean): Extra validation check, default false is sufficient

Notes:

  • Win/Xbox platform only

Example:

crashSight.uploadGivenPathDump('C:\\dumps', false);

unrealCriticalErrorEnable(enable)

Enable/disable Unreal Critical Error reporting.

Parameters:

  • enable (boolean): Whether to enable

Notes:

  • Win/Xbox platform only
  • For Unreal Engine projects

Example:

crashSight.unrealCriticalErrorEnable(true);

onlyUploadFirstCrash(enable)

Enable report only the first crash.

Parameters:

  • enable (boolean): Whether to report only the first crash

Notes:

  • Win/Xbox platform only
  • Only takes effect after VEH capture is enabled

Example:

crashSight.onlyUploadFirstCrash(true);

setDumpType(dumpType)

Set dump type.

Parameters:

  • dumpType (number): Dump type, see Windows official definition

Notes:

  • Win/Xbox platform only
  • Please consult CrashSight developers before using

Example:

crashSight.setDumpType(1);

addValidExpCode(expCode)

Add valid exception code.

Parameters:

  • expCode (number): Exception code, see Windows official definition

Notes:

  • Win/Xbox platform only
  • Please consult CrashSight developers before using

Example:

crashSight.addValidExpCode(0xC0000005);

uploadCrashWithGuid(guid)

Upload crash with GUID.

Parameters:

  • guid (string): GUID identifying the specific issue, can be obtained through callback

Notes:

  • Win/Xbox platform only

Example:

crashSight.uploadCrashWithGuid('12345678-1234-1234-1234-123456789abc');

setCrashUploadEnable(enable)

Set crash upload enable status.

Parameters:

  • enable (boolean): Whether to enable crash upload

Notes:

  • Win/Xbox platform only

Example:

crashSight.setCrashUploadEnable(true);

setWorkSpace(workspace)

Set workspace.

Parameters:

  • workspace (string): Absolute path of workspace

Notes:

  • Win/Xbox platform only
  • Does not support GBK character paths (use setWorkSpaceW if needed)

Example:

crashSight.setWorkSpace('C:\\workspace');

setWorkSpaceW(workspace)

Set workspace (wide char version, supports GBK characters).

Parameters:

  • workspace (string): Absolute path of workspace (supports Chinese and other GBK characters)

Notes:

  • Win/Xbox platform only

Example:

crashSight.setWorkSpaceW('D:\\中文workspace');

setAttachPath(attachPath)

Set custom attachment path.

Parameters:

  • attachPath (string): Absolute path to attachment directory

Notes:

  • Win/Xbox platform only
  • Does not support GBK character paths (use setAttachPathW if needed)

Example:

crashSight.setAttachPath('C:\\attachments');

setAttachPathW(attachPath)

Set custom attachment path (wide char version, supports GBK characters).

Parameters:

  • attachPath (string): Absolute path to attachment directory (supports Chinese and other GBK characters)

Notes:

  • Win/Xbox platform only

Example:

crashSight.setAttachPathW('D:\\中文附件路径');

7.6 Other APIs

printLog(level, tag, format, ...args)

Add custom logs.

Parameters:

  • level (number): Log level (0-4, corresponding to Off/Error/Warn/Info/Debug)
  • tag (string): Log tag
  • format (string): Format string, supports {0}, {1} placeholders
  • ...args: Variable arguments for replacing placeholders in format string

Notes:

  • Custom log limit: 30KB
  • Custom log view: Issue Details -> Custom Log (from interface)

Example:

crashSight.printLog(
CrashSightLogLevel.CSLogLevelInfo,
'MyTag',
'User {0} completed level {1}',
'user123',
10
);

testNativeCrash()

Test native crash.

Notes:

  • Used to test crash capture functionality
  • Warning: Calling this method will cause the application to crash immediately

Example:

crashSight.testNativeCrash();  // Application will crash immediately

setEngineInfo(version?, buildConfig?, language?, locale?)

Set engine information (automatically called by plugin).

Parameters:

  • version (string, optional): Engine version
  • buildConfig (string, optional): Build configuration
  • language (string, optional): Language
  • locale (string, optional): Locale

Notes:

  • Usually automatically called by plugin, no need to set manually
  • Automatically detects Electron and Node.js version information

getCrashThreadId()

Get crashed thread ID.

Returns:

  • number: Thread ID of crashed thread, returns -1 if failed

Notes:

  • Win/Xbox platform only

Example:

const threadId = crashSight.getCrashThreadId();

getSessionId()

Get SDK-generated session ID.

Returns:

  • string: Session ID string

Example:

const sessionId = crashSight.getSessionId();

setCrashObserver(crashObserver)

Set crash observer.

Parameters:

  • crashObserver (object): Crash observer object (needs to implement specific interface)

Notes:

  • This interface may not be fully supported in current Electron version
  • Recommend using setCrashCallback instead

reportStuck(threadId, maxChecks, checkInterval, name, message, extraInfo, dumpNativeType, attachPath)

Report jank/stuck.

Parameters:

  • threadId (number): Thread ID
  • maxChecks (number): Maximum check count
  • checkInterval (number): Check interval (milliseconds)
  • name (string): Exception name
  • message (string): Exception message
  • extraInfo (string): Extra information
  • dumpNativeType (number): Dump type
  • attachPath (string): Attachment path

Notes:

  • Used to report thread stuck issues

Example:

crashSight.reportStuck(
12345, // threadId
10, // maxChecks
1000, // checkInterval (ms)
'ThreadStuck',
'Main thread stuck for 10 seconds',
JSON.stringify({ scene: 'loading' }),
0, // dumpNativeType
'' // attachPath
);

7.7 Log Level Enum

const CrashSightLogLevel = {
CSLogLevelSilent: 0, // Off
CSLogLevelError: 1, // Error
CSLogLevelWarn: 2, // Warn
CSLogLevelInfo: 3, // Info (default)
CSLogLevelDebug: 4, // Debug
CSLogLevelVerbose: 5 // Verbose
};

Step 8: Frequently Asked Questions

Q1: What to do if compilation fails during installation?

A: Ensure you have installed:

  • Windows: Visual Studio 2019/2022 or Windows Build Tools
  • Run npm install --global windows-build-tools (if using npm)

Q2: DLL cannot be loaded after packaging?

A: Check the following:

  1. Ensure asarUnpack configuration is correct
  2. Check if DLL files exist in the app.asar.unpacked directory after packaging
  3. Verify that the DLL path is correct

Q3: Exceptions are not being captured?

A:

  • Ensure initWithAppId() has been successfully called
  • Exceptions must be thrown in the main process
  • Renderer process exceptions will not be automatically captured (only main process exceptions are captured)

Q4: How to check if reporting is successful?

A:

  • Log in to the CrashSight console to view reporting records
  • Check log files (if log path is configured)

Q5: Which Electron versions are supported?

A:

  • Tested Versions (all passed):

    Electron VersionNode.js VersionStatus
    16.2.016.14.2✅ Passed
    18.3.016.14.2✅ Passed
    20.3.016.15.0✅ Passed
    22.3.018.15.0✅ Passed
    27.3.018.17.1✅ Passed
  • Compatibility Notes:

    • This plugin uses N-API, theoretically supporting Electron 16+ and Node.js 16+
    • All tested versions passed installation, compilation, and module loading tests
    • Test pass rate: 100% (5/5)
  • If using other versions:

    1. Run npx electron-rebuild to recompile the native module
    2. Test basic functionality
    3. If issues occur, check if the Electron version is too old (recommended 16+)