This module provides automatic instrumentation for capturing unhandled exceptions and promise rejections in web applications.
npm install --save @opentelemetry/instrumentation-web-exception
import { LoggerProvider } from '@opentelemetry/sdk-logs';
import { EventLoggerProvider, events } from '@opentelemetry/api-events';
import { WebExceptionInstrumentation } from '@opentelemetry/instrumentation-web-exception';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
// Set up the logger provider and event logger
const loggerProvider = new LoggerProvider();
const eventLoggerProvider = new EventLoggerProvider(loggerProvider);
events.setGlobalEventLoggerProvider(eventLoggerProvider);
// Register the instrumentation
registerInstrumentations({
instrumentations: [
new WebExceptionInstrumentation({
// Optional: customize attributes added to error events
applyCustomAttributes: (error) => ({
'app.error.severity': error.name === 'ValidationError' ? 'warning' : 'error',
'custom.correlation.id': window.correlationId,
}),
}),
],
});
The instrumentation can be configured with the following options:
Option | Type | Description |
---|---|---|
enabled |
boolean |
Whether to enable the instrumentation. Default: true |
applyCustomAttributes |
(error: Error) => Attributes |
Optional callback to add custom attributes to error events |
- Automatically captures unhandled exceptions
- Captures unhandled promise rejections
- Records error name, message, and stack trace using OpenTelemetry semantic conventions
- Supports custom attributes through configuration
- Integrates with OpenTelemetry Events API
The following semantic attributes are added to each error event:
Attribute | Type | Description |
---|---|---|
exception.type |
string | The error name or type |
exception.message |
string | The error message |
exception.stacktrace |
string | The error stack trace |
// Initialize the instrumentation
const exceptionInstrumentation = new WebExceptionInstrumentation({
applyCustomAttributes: (error) => ({
'error.category': error instanceof TypeError ? 'type_error' : 'runtime_error',
'app.version': '1.0.0',
}),
});
// The instrumentation will automatically capture unhandled errors
throw new Error('Unhandled error');
// And unhandled promise rejections
Promise.reject(new Error('Unhandled rejection'));
- For more information on OpenTelemetry, visit: https://opentelemetry.io/
- For more about OpenTelemetry JavaScript: https://github.com/open-telemetry/opentelemetry-js
- For help or feedback on this project, join us in GitHub Discussions
Apache 2.0 - See LICENSE for more information.