Automatic catching and logging of unhandled exceptions and promise rejections with customizable error processing, dialog display, and error reporting integration.
Core error handling functionality for catching and processing unhandled errors.
interface ErrorHandler<T = ErrorHandlerOptions> {
/**
* Process an error by the ErrorHandler
* @param error - Error to process
* @param options - Processing options
*/
handle(error: Error, options?: T): void;
/**
* Change some options
* @param options - New error handler options
*/
setOptions(options: T): void;
/**
* Start catching unhandled errors and rejections
* @param options - Configuration options
*/
startCatching(options?: T): void;
/**
* Stop catching unhandled errors and rejections
*/
stopCatching(): void;
}Usage Examples:
const log = require('electron-log');
// Start catching unhandled errors
log.errorHandler.startCatching();
// Handle specific error manually
try {
throw new Error('Manual error');
} catch (error) {
log.errorHandler.handle(error, {
showDialog: false
});
}
// Configure error handler
log.errorHandler.setOptions({
showDialog: true,
onError: ({ error, errorName, processType, versions, createIssue }) => {
console.log('Error caught:', errorName, error.message);
// Custom error processing
if (error.message.includes('CRITICAL')) {
// Send to error reporting service
sendToErrorReporting(error);
}
// Create GitHub issue
if (processType === 'browser') {
createIssue('https://github.com/myapp/myapp/issues/new', {
title: `${errorName}: ${error.message}`,
body: `Error: ${error.stack}\n\nVersions: ${JSON.stringify(versions)}`
});
}
}
});
// Stop error catching
log.errorHandler.stopCatching();Enhanced error handling for main process with dialog support and version information.
interface MainErrorHandlerOptions extends ErrorHandlerOptions {
/**
* Default true for the main process. Set it to false to prevent showing a
* default electron error dialog
*/
showDialog?: boolean;
/**
* Attach a custom error handler. If the handler returns false, this error
* will not be processed
*/
onError?(options: {
createIssue: (url: string, data: ReportData | any) => void;
error: Error;
errorName: 'Unhandled' | 'Unhandled rejection';
processType: 'browser' | 'renderer';
versions: { app: string; electron: string; os: string };
}): void;
}Usage Examples:
// Main process
const log = require('electron-log/main');
log.errorHandler.setOptions({
showDialog: true, // Show Electron error dialog
onError: ({ error, errorName, processType, versions, createIssue }) => {
// Log error with full context
log.error('Unhandled error:', {
name: errorName,
message: error.message,
stack: error.stack,
processType,
versions
});
// Conditional processing
if (error.name === 'TypeError') {
// Handle type errors specifically
log.warn('Type error detected, checking configuration...');
}
// Auto-report critical errors
if (error.message.includes('ENOENT') || error.message.includes('permission denied')) {
createIssue('https://github.com/myapp/issues/new', {
title: `${errorName}: File system error`,
body: `${error.stack}\n\nOS: ${versions.os}\nElectron: ${versions.electron}`,
labels: 'bug,filesystem'
});
}
}
});
log.errorHandler.startCatching();Renderer-specific error handling with event prevention control.
interface RendererErrorHandlerOptions extends ErrorHandlerOptions {
/**
* By default, error and unhandledrejection handlers call preventDefault to
* prevent error duplicating in console. Set false to disable it
*/
preventDefault?: boolean;
/**
* Attach a custom error handler. If the handler returns false, this error
* will not be processed
*/
onError?(options: {
error: Error;
errorName: 'Unhandled' | 'Unhandled rejection';
processType: 'browser' | 'renderer';
}): void;
}Usage Examples:
// Renderer process
const log = require('electron-log/renderer');
log.errorHandler.setOptions({
preventDefault: true, // Prevent console duplication
onError: ({ error, errorName, processType }) => {
// Send error info to main process
if (window.electronAPI) {
window.electronAPI.reportError({
error: error.message,
stack: error.stack,
processType
});
}
// Custom renderer error handling
if (error.name === 'ChunkLoadError') {
log.warn('Chunk load error, attempting reload...');
window.location.reload();
return false; // Prevent further processing
}
}
});
log.errorHandler.startCatching();Integration with external error reporting services and issue tracking.
interface ReportData {
body: string;
title: string;
assignee: string;
labels: string;
milestone: string;
projects: string;
template: string;
}
type CreateIssueFunction = (url: string, data: ReportData | any) => void;Usage Examples:
const log = require('electron-log');
log.errorHandler.setOptions({
onError: ({ error, createIssue, versions }) => {
// GitHub issue creation
createIssue('https://github.com/myorg/myapp/issues/new', {
title: `Bug: ${error.message}`,
body: `
**Error Details:**
- Message: ${error.message}
- Stack: \`\`\`\n${error.stack}\n\`\`\`
- App Version: ${versions.app}
- Electron Version: ${versions.electron}
- OS: ${versions.os}
**Steps to Reproduce:**
<!-- Please fill this out -->
**Expected Behavior:**
<!-- Please fill this out -->
`,
labels: 'bug,auto-generated',
assignee: 'maintainer-username'
});
// Send to external error service
fetch('https://api.errorservice.com/errors', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
error: error.message,
stack: error.stack,
metadata: {
versions,
timestamp: new Date().toISOString(),
userId: app.getPath('userData')
}
})
});
}
});Deprecated methods maintained for backward compatibility.
interface LegacyErrorHandler {
/**
* Catch and log unhandled errors/rejected promises
* @deprecated Use errorHandler.startCatching() instead
*/
catchErrors(options?: ErrorHandlerOptions): ErrorHandler;
}Usage Examples:
const log = require('electron-log');
// Legacy method (deprecated)
const errorHandler = log.catchErrors({
showDialog: false,
onError: (error) => {
log.error('Legacy error handler:', error);
}
});
// Modern equivalent
log.errorHandler.startCatching({
showDialog: false,
onError: ({ error }) => {
log.error('Modern error handler:', error);
}
});Advanced error processing with filtering and custom logic.
interface ErrorProcessingOptions {
/** Filter function to determine if error should be processed */
shouldProcess?: (error: Error) => boolean;
/** Transform error before processing */
transformError?: (error: Error) => Error;
/** Custom logging function */
logError?: (error: Error, context: any) => void;
}Usage Examples:
const log = require('electron-log');
log.errorHandler.setOptions({
onError: ({ error, errorName }) => {
// Filter out known harmless errors
const harmlessErrors = ['ResizeObserver loop limit exceeded', 'Non-Error promise rejection captured'];
if (harmlessErrors.some(msg => error.message.includes(msg))) {
return false; // Don't process
}
// Enhance error with additional context
const enhancedError = new Error(error.message);
enhancedError.stack = error.stack;
enhancedError.timestamp = new Date().toISOString();
enhancedError.processMemory = process.memoryUsage();
enhancedError.originalError = error;
// Custom categorization
let category = 'unknown';
if (error.name === 'TypeError') category = 'type-error';
if (error.message.includes('network')) category = 'network';
if (error.message.includes('permission')) category = 'permission';
log.error(`[${category}] ${errorName}:`, enhancedError);
}
});interface ErrorHandlerOptions {
/**
* Default true for the main process. Set it to false to prevent showing a
* default electron error dialog
*/
showDialog?: boolean;
/**
* Attach a custom error handler. If the handler returns false, this error
* will not be processed
*/
onError?(options: {
createIssue: (url: string, data: ReportData | any) => void;
error: Error;
errorName: 'Unhandled' | 'Unhandled rejection';
processType: 'browser' | 'renderer';
versions?: { app: string; electron: string; os: string };
}): void;
}
interface MainErrorHandlerOptions extends ErrorHandlerOptions {
onError?(options: {
createIssue: (url: string, data: ReportData | any) => void;
error: Error;
errorName: 'Unhandled' | 'Unhandled rejection';
processType: 'browser' | 'renderer';
versions: { app: string; electron: string; os: string };
}): void;
}
interface RendererErrorHandlerOptions extends ErrorHandlerOptions {
preventDefault?: boolean;
onError?(options: {
error: Error;
errorName: 'Unhandled' | 'Unhandled rejection';
processType: 'browser' | 'renderer';
}): void;
}
interface ReportData {
body: string;
title: string;
assignee: string;
labels: string;
milestone: string;
projects: string;
template: string;
}