@sentry/core
- Version 8.42.0
- Published
- 3.53 MB
- No dependencies
- MIT license
Install
npm i @sentry/core
yarn add @sentry/core
pnpm add @sentry/core
Overview
Base implementation for all Sentry JavaScript SDKs
Index
Variables
- BAGGAGE_HEADER_NAME
- browserPerformanceTimeOrigin
- CONSOLE_LEVELS
- DEFAULT_ENVIRONMENT
- DEFAULT_RETRY_AFTER
- DEFAULT_USER_INCLUDES
- getCurrentHub
- GLOBAL_OBJ
- logger
- MAX_BAGGAGE_STRING_LENGTH
- metrics
- metricsDefault
- originalConsoleMethods
- profiler
- Scope
- SDK_VERSION
- SEMANTIC_ATTRIBUTE_CACHE_HIT
- SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE
- SEMANTIC_ATTRIBUTE_CACHE_KEY
- SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME
- SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD
- SEMANTIC_ATTRIBUTE_PROFILE_ID
- SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON
- SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT
- SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE
- SEMANTIC_ATTRIBUTE_SENTRY_OP
- SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN
- SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE
- SEMANTIC_ATTRIBUTE_SENTRY_SOURCE
- SEMANTIC_ATTRIBUTE_URL_FULL
- SENTRY_BAGGAGE_KEY_PREFIX
- SENTRY_BAGGAGE_KEY_PREFIX_REGEX
- SPAN_STATUS_ERROR
- SPAN_STATUS_OK
- SPAN_STATUS_UNSET
- TRACEPARENT_REGEXP
- TRACING_DEFAULTS
- UNKNOWN_FUNCTION
- validSeverityLevels
Functions
- addBreadcrumb()
- addChildSpanToSpan()
- addConsoleInstrumentationHandler()
- addContextToFrame()
- addEventProcessor()
- addExceptionMechanism()
- addExceptionTypeValue()
- addFetchEndInstrumentationHandler()
- addFetchInstrumentationHandler()
- addGlobalErrorInstrumentationHandler()
- addGlobalUnhandledRejectionInstrumentationHandler()
- addHandler()
- addIntegration()
- addItemToEnvelope()
- addNonEnumerableProperty()
- addNormalizedRequestDataToEvent()
- addRequestDataToEvent()
- addTracingExtensions()
- addTracingHeadersToFetchRequest()
- applyAggregateErrorsToEvent()
- applyScopeDataToEvent()
- applySdkMetadata()
- arrayify()
- baggageHeaderToDynamicSamplingContext()
- basename()
- callFrameToStackFrame()
- captureCheckIn()
- captureConsoleIntegration()
- captureEvent()
- captureException()
- captureFeedback()
- captureMessage()
- captureSession()
- checkOrSetAlreadyCaught()
- close()
- closeSession()
- consoleSandbox()
- continueTrace()
- convertToPlainObject()
- createAttachmentEnvelopeItem()
- createCheckInEnvelope()
- createClientReportEnvelope()
- createEnvelope()
- createEventEnvelope()
- createEventEnvelopeHeaders()
- createSessionEnvelope()
- createSpanEnvelope()
- createSpanEnvelopeItem()
- createStackParser()
- createTransport()
- dateTimestampInSeconds()
- debugIntegration()
- dedupeIntegration()
- defineIntegration()
- dirname()
- disabledUntil()
- dropUndefinedKeys()
- dsnFromString()
- dsnToString()
- dynamicRequire()
- dynamicSamplingContextToSentryBaggageHeader()
- endSession()
- envelopeContainsItemType()
- envelopeItemTypeToDataCategory()
- escapeStringForRegex()
- eventFromMessage()
- eventFromUnknownInput()
- exceptionFromError()
- extractExceptionKeysForMessage()
- extractPathForTransaction()
- extractQueryParamsFromUrl()
- extractRequestData()
- extractTraceparentData()
- extraErrorDataIntegration()
- filenameIsInApp()
- fill()
- flatten()
- flush()
- forEachEnvelopeItem()
- functionToStringIntegration()
- generatePropagationContext()
- generateSentryTraceHeader()
- generateSpanId()
- generateTraceId()
- getActiveSpan()
- getBreadcrumbLogLevelFromHttpStatusCode()
- getCapturedScopesOnSpan()
- getClient()
- getComponentName()
- getCurrentHubShim()
- getCurrentScope()
- getDebugImagesForResources()
- getDefaultCurrentScope()
- getDefaultIsolationScope()
- getDomElement()
- getDynamicSamplingContextFromClient()
- getDynamicSamplingContextFromScope()
- getDynamicSamplingContextFromSpan()
- getEnvelopeEndpointWithUrlEncodedAuth()
- getEventDescription()
- getFilenameToDebugIdMap()
- getFramesFromEvent()
- getFunctionName()
- getGlobalScope()
- getGlobalSingleton()
- getIntegrationsToSetup()
- getIsolationScope()
- getLocationHref()
- getMainCarrier()
- getMetricSummaryJsonForSpan()
- getNumberOfUrlSegments()
- getOriginalFunction()
- getReportDialogEndpoint()
- getRootSpan()
- getSanitizedUrlString()
- getSdkMetadataForEnvelopeHeader()
- getSDKSource()
- getSpanDescendants()
- getSpanStatusFromHttpCode()
- getStatusMessage()
- getTraceContextFromScope()
- getTraceData()
- getTraceMetaTags()
- handleCallbackErrors()
- hasTracingEnabled()
- headersToDict()
- htmlTreeAsString()
- httpRequestToRequestData()
- inboundFiltersIntegration()
- initAndBind()
- instrumentFetchRequest()
- isAbsolute()
- isBrowser()
- isBrowserBundle()
- isDOMError()
- isDOMException()
- isElement()
- isEnabled()
- isError()
- isErrorEvent()
- isEvent()
- isInitialized()
- isInstanceOf()
- isMatchingPattern()
- isNativeFunction()
- isNodeEnv()
- isParameterizedString()
- isPlainObject()
- isPrimitive()
- isRateLimited()
- isRegExp()
- isSentryRequestUrl()
- isString()
- isSyntheticEvent()
- isThenable()
- isVueViewModel()
- join()
- lastEventId()
- linkedErrorsIntegration()
- loadModule()
- logSpanEnd()
- logSpanStart()
- makeDsn()
- makeFifoCache()
- makeMultiplexedTransport()
- makeOfflineTransport()
- makePromiseBuffer()
- makeSession()
- markFunctionWrapped()
- maybeInstrument()
- memoBuilder()
- mergeScopeData()
- moduleMetadataIntegration()
- node()
- nodeStackLineParser()
- normalize()
- normalizePath()
- normalizeToSize()
- normalizeUrlToBase()
- notifyEventProcessors()
- objectify()
- parameterize()
- parseBaggageHeader()
- parseEnvelope()
- parseRetryAfterHeader()
- parseSampleRate()
- parseSemver()
- parseStackFrames()
- parseUrl()
- prepareEvent()
- propagationContextFromHeaders()
- registerSpanErrorInstrumentation()
- rejectedSyncPromise()
- relative()
- requestDataIntegration()
- resetInstrumentationHandlers()
- resolve()
- resolvedSyncPromise()
- rewriteFramesIntegration()
- safeJoin()
- sampleSpan()
- serializeEnvelope()
- sessionTimingIntegration()
- setAsyncContextStrategy()
- setCapturedScopesOnSpan()
- setContext()
- setCurrentClient()
- setExtra()
- setExtras()
- setHttpStatus()
- setMeasurement()
- setTag()
- setTags()
- setUser()
- severityLevelFromString()
- snipLine()
- spanIsSampled()
- spanTimeInputToSeconds()
- spanToBaggageHeader()
- spanToJSON()
- spanToTraceContext()
- spanToTraceHeader()
- stackParserFromStackParserOptions()
- startIdleSpan()
- startInactiveSpan()
- startNewTrace()
- startSession()
- startSpan()
- startSpanManual()
- stringMatchesSomePattern()
- stripSentryFramesAndReverse()
- stripUrlQueryAndFragment()
- supportsDOMError()
- supportsDOMException()
- supportsErrorEvent()
- supportsFetch()
- supportsHistory()
- supportsNativeFetch()
- supportsReferrerPolicy()
- supportsReportingObserver()
- suppressTracing()
- thirdPartyErrorFilterIntegration()
- timedEventsToMeasurements()
- timestampInSeconds()
- triggerHandlers()
- trpcMiddleware()
- truncate()
- updateRateLimits()
- updateSession()
- urlEncode()
- uuid4()
- vercelWaitUntil()
- watchdogTimer()
- winterCGHeadersToDict()
- winterCGRequestToRequestData()
- withActiveSpan()
- withIsolationScope()
- withMonitor()
- withScope()
- zodErrorsIntegration()
Classes
BaseClient
- addEventProcessor()
- addIntegration()
- captureEvent()
- captureException()
- captureMessage()
- captureSession()
- close()
- emit()
- eventFromException()
- eventFromMessage()
- flush()
- getDsn()
- getEventProcessors()
- getIntegrationByName()
- getOptions()
- getSdkMetadata()
- getTransport()
- init()
- on()
- recordDroppedEvent()
- sendEnvelope()
- sendEvent()
- sendSession()
Interfaces
Client
- addEventProcessor()
- addIntegration()
- captureCheckIn()
- captureEvent()
- captureException()
- captureMessage()
- captureSession()
- close()
- emit()
- eventFromException()
- eventFromMessage()
- flush()
- getDsn()
- getEventProcessors()
- getIntegrationByName()
- getOptions()
- getSdkMetadata()
- getTransport()
- init()
- on()
- recordDroppedEvent()
- sendEnvelope()
- sendEvent()
- sendSession()
ClientOptions
- allowUrls
- attachStacktrace
- autoSessionTracking
- beforeBreadcrumb
- beforeSend
- beforeSendSpan
- beforeSendTransaction
- debug
- denyUrls
- dist
- dsn
- enabled
- enableTracing
- environment
- ignoreErrors
- ignoreTransactions
- initialScope
- integrations
- maxBreadcrumbs
- maxValueLength
- normalizeDepth
- normalizeMaxBreadth
- parentSpanIsAlwaysRootSpan
- release
- sampleRate
- sendClientReports
- sendDefaultPii
- shutdownTimeout
- stackParser
- tracePropagationTargets
- tracesSampler
- tracesSampleRate
- transport
- transportOptions
- tunnel
DeviceContext
- arch
- battery_level
- battery_status
- boot_time
- brand
- charging
- cpu_description
- device_type
- device_unique_identifier
- external_free_storage
- external_storage_size
- family
- free_memory
- free_storage
- low_memory
- manufacturer
- memory_size
- model
- model_id
- name
- online
- orientation
- processor_count
- processor_frequency
- screen_density
- screen_dpi
- screen_height_pixels
- screen_resolution
- screen_width_pixels
- simulator
- storage_size
- supports_accelerometer
- supports_audio
- supports_gyroscope
- supports_location_service
- supports_vibration
- usable_memory
Type Aliases
- AddRequestDataToEventOptions
- AttachmentItem
- BaseEnvelopeHeaders
- BaseEnvelopeItemHeaders
- BrowserClientProfilingOptions
- BrowserClientReplayOptions
- CaptureContext
- CheckIn
- CheckInEnvelope
- CheckInItem
- ClientReport
- ClientReportEnvelope
- ClientReportItem
- ConsoleLevel
- Context
- DataCategory
- DebugImage
- DsnLike
- DsnProtocol
- DurationUnit
- DynamicSamplingContext
- Envelope
- EnvelopeItem
- EnvelopeItemType
- EventDropReason
- EventEnvelope
- EventEnvelopeHeaders
- EventItem
- EventType
- Extra
- Extras
- FeedbackFormData
- FeedbackItem
- FractionUnit
- FrameId
- HandlerDataUnhandledRejection
- HttpHeaderValue
- InformationUnit
- IntegrationFn
- IntegrationIndex
- InternalGlobal
- Measurements
- MeasurementUnit
- MetricSummary
- NoneUnit
- Outcome
- ParameterizedString
- PolymorphicRequest
- Primitive
- ProfileChunkEnvelope
- ProfileChunkItem
- ProfileItem
- QueryParams
- RateLimits
- ReplayEnvelope
- ReplayRecordingData
- ReplayRecordingMode
- Request
- RequestDataIntegrationOptions
- RequestSessionStatus
- SanitizedRequestData
- Scope
- SdkSource
- SendFeedback
- SentryCoreCurrentScopes
- SessionContext
- SessionEnvelope
- SessionItem
- SessionStatus
- SeverityLevel
- SpanAttributes
- SpanAttributeValue
- SpanEnvelope
- SpanItem
- SpanOrigin
- SpanTimeInput
- StackId
- StackLineParser
- StackLineParserFn
- StackParser
- StatsdEnvelope
- StatsdItem
- ThreadCpuFrame
- ThreadCpuStack
- ThreadId
- TraceFlag
- TracePropagationTargets
- TransactionNamingScheme
- TransactionSource
- TransportMakeRequestResponse
- TransportRequest
- TransportRequestExecutor
- UserFeedbackItem
- ViewHierarchyData
- ViewHierarchyWindow
- WrappedFunction
Variables
variable BAGGAGE_HEADER_NAME
const BAGGAGE_HEADER_NAME: string;
Deprecated
Use a
"baggage"
string directly
variable browserPerformanceTimeOrigin
const browserPerformanceTimeOrigin: number;
The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the performance API is available.
variable CONSOLE_LEVELS
const CONSOLE_LEVELS: readonly ConsoleLevel[];
variable DEFAULT_ENVIRONMENT
const DEFAULT_ENVIRONMENT: string;
variable DEFAULT_RETRY_AFTER
const DEFAULT_RETRY_AFTER: number;
variable DEFAULT_USER_INCLUDES
const DEFAULT_USER_INCLUDES: string[];
variable getCurrentHub
const getCurrentHub: () => Hub;
Returns the default hub instance.
If a hub is already registered in the global carrier but this module contains a more recent version, it replaces the registered version. Otherwise, the currently registered hub will be returned.
Deprecated
Use the respective replacement method directly instead.
variable GLOBAL_OBJ
const GLOBAL_OBJ: InternalGlobal;
Get's the global object for the current JavaScript runtime
variable logger
const logger: Logger;
This is a logger singleton which either logs things or no-ops if logging is not enabled. The logger is a singleton on the carrier, to ensure that a consistent logger is used throughout the SDK.
variable MAX_BAGGAGE_STRING_LENGTH
const MAX_BAGGAGE_STRING_LENGTH: number;
Max length of a serialized baggage string
https://www.w3.org/TR/baggage/#limits
variable metrics
const metrics: { increment: typeof increment; distribution: typeof distribution; set: typeof set; gauge: typeof gauge; timing: typeof timing; getMetricsAggregatorForClient: typeof getMetricsAggregatorForClient;};
The metrics API is used to capture custom metrics in Sentry.
Deprecated
The Sentry metrics beta has ended. This export will be removed in a future release.
variable metricsDefault
const metricsDefault: Metrics & { getMetricsAggregatorForClient: typeof getMetricsAggregatorForClient;};
The metrics API is used to capture custom metrics in Sentry.
Deprecated
The Sentry metrics beta has ended. This export will be removed in a future release.
variable originalConsoleMethods
const originalConsoleMethods: { error?: (...args: any[]) => void; log?: (...args: any[]) => void; info?: (...args: any[]) => void; debug?: (...args: any[]) => void; warn?: (...args: any[]) => void; assert?: (...args: any[]) => void; trace?: (...args: any[]) => void;};
This may be mutated by the console instrumentation.
variable profiler
const profiler: Profiler;
variable Scope
const Scope: typeof ScopeClass;
Holds additional event information.
variable SDK_VERSION
const SDK_VERSION: string;
variable SEMANTIC_ATTRIBUTE_CACHE_HIT
const SEMANTIC_ATTRIBUTE_CACHE_HIT: string;
variable SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE
const SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE: string;
variable SEMANTIC_ATTRIBUTE_CACHE_KEY
const SEMANTIC_ATTRIBUTE_CACHE_KEY: string;
variable SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME
const SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME: string;
variable SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD
const SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD: string;
TODO: Remove these once we update to latest semantic conventions
variable SEMANTIC_ATTRIBUTE_PROFILE_ID
const SEMANTIC_ATTRIBUTE_PROFILE_ID: string;
The id of the profile that this span occurred in.
variable SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON
const SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON: string;
The reason why an idle span finished.
variable SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT
const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT: string;
The unit of a measurement, which may be stored as a TimedEvent.
variable SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE
const SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE: string;
The value of a measurement, which may be stored as a TimedEvent.
variable SEMANTIC_ATTRIBUTE_SENTRY_OP
const SEMANTIC_ATTRIBUTE_SENTRY_OP: string;
Use this attribute to represent the operation of a span.
variable SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN
const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN: string;
Use this attribute to represent the origin of a span.
variable SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE
const SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE: string;
Use this attribute to represent the sample rate used for a span.
variable SEMANTIC_ATTRIBUTE_SENTRY_SOURCE
const SEMANTIC_ATTRIBUTE_SENTRY_SOURCE: string;
Use this attribute to represent the source of a span. Should be one of: custom, url, route, view, component, task, unknown
variable SEMANTIC_ATTRIBUTE_URL_FULL
const SEMANTIC_ATTRIBUTE_URL_FULL: string;
variable SENTRY_BAGGAGE_KEY_PREFIX
const SENTRY_BAGGAGE_KEY_PREFIX: string;
variable SENTRY_BAGGAGE_KEY_PREFIX_REGEX
const SENTRY_BAGGAGE_KEY_PREFIX_REGEX: RegExp;
variable SPAN_STATUS_ERROR
const SPAN_STATUS_ERROR: number;
variable SPAN_STATUS_OK
const SPAN_STATUS_OK: number;
variable SPAN_STATUS_UNSET
const SPAN_STATUS_UNSET: number;
variable TRACEPARENT_REGEXP
const TRACEPARENT_REGEXP: RegExp;
variable TRACING_DEFAULTS
const TRACING_DEFAULTS: { idleTimeout: number; finalTimeout: number; childSpanTimeout: number;};
variable UNKNOWN_FUNCTION
const UNKNOWN_FUNCTION: string;
variable validSeverityLevels
const validSeverityLevels: string[];
Deprecated
This variable has been deprecated and will be removed in the next major version.
Functions
function addBreadcrumb
addBreadcrumb: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void;
Records a new breadcrumb which will be attached to future events.
Breadcrumbs will be added to subsequent events to provide more context on user's actions prior to an error or crash.
function addChildSpanToSpan
addChildSpanToSpan: (span: SpanWithPotentialChildren, childSpan: Span) => void;
Adds an opaque child span reference to a span.
function addConsoleInstrumentationHandler
addConsoleInstrumentationHandler: ( handler: (data: HandlerDataConsole) => void) => void;
Add an instrumentation handler for when a console.xxx method is called.
Use at your own risk, this might break without changelog notice, only used internally.
function addContextToFrame
addContextToFrame: ( lines: string[], frame: StackFrame, linesOfContext?: number) => void;
This function adds context (pre/post/line) lines to the provided frame
Parameter lines
string[] containing all lines
Parameter frame
StackFrame that will be mutated
Parameter linesOfContext
number of context lines we want to add pre/post
function addEventProcessor
addEventProcessor: (callback: EventProcessor) => void;
Add an event processor. This will be added to the current isolation scope, ensuring any event that is processed in the current execution context will have the processor applied.
function addExceptionMechanism
addExceptionMechanism: (event: Event, newMechanism?: Partial<Mechanism>) => void;
Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.
Parameter event
The event to modify.
Parameter newMechanism
Mechanism data to add to the event.
function addExceptionTypeValue
addExceptionTypeValue: (event: Event, value?: string, type?: string) => void;
Adds exception values, type and value to an synthetic Exception.
Parameter event
The event to modify.
Parameter value
Value of the exception.
Parameter type
Type of the exception.
function addFetchEndInstrumentationHandler
addFetchEndInstrumentationHandler: ( handler: (data: HandlerDataFetch) => void) => void;
Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch. The handler will resolve the request body and emit the actual
endTimestamp
, so that the span can be updated accordingly.Only used internally
function addFetchInstrumentationHandler
addFetchInstrumentationHandler: ( handler: (data: HandlerDataFetch) => void, skipNativeFetchCheck?: boolean) => void;
Add an instrumentation handler for when a fetch request happens. The handler function is called once when the request starts and once when it ends, which can be identified by checking if it has an
endTimestamp
.Use at your own risk, this might break without changelog notice, only used internally.
function addGlobalErrorInstrumentationHandler
addGlobalErrorInstrumentationHandler: ( handler: (data: HandlerDataError) => void) => void;
Add an instrumentation handler for when an error is captured by the global error handler.
Use at your own risk, this might break without changelog notice, only used internally.
function addGlobalUnhandledRejectionInstrumentationHandler
addGlobalUnhandledRejectionInstrumentationHandler: ( handler: (data: HandlerDataUnhandledRejection) => void) => void;
Add an instrumentation handler for when an unhandled promise rejection is captured.
Use at your own risk, this might break without changelog notice, only used internally.
function addHandler
addHandler: ( type: InstrumentHandlerType, handler: InstrumentHandlerCallback) => void;
Add a handler function.
function addIntegration
addIntegration: (integration: Integration) => void;
Add an integration to the current scope's client.
function addItemToEnvelope
addItemToEnvelope: <E extends Envelope>(envelope: E, newItem: E[1][number]) => E;
Add an item to an envelope. Make sure to always explicitly provide the generic to this function so that the envelope types resolve correctly.
function addNonEnumerableProperty
addNonEnumerableProperty: (obj: object, name: string, value: unknown) => void;
Defines a non-enumerable property on the given object.
Parameter obj
The object on which to set the property
Parameter name
The name of the property to be set
Parameter value
The value to which to set the property
function addNormalizedRequestDataToEvent
addNormalizedRequestDataToEvent: ( event: Event, req: RequestEventData, additionalData: { ipAddress?: string; user?: Record<string, unknown> }, options: AddRequestDataToEventOptions) => void;
Add already normalized request data to an event. This mutates the passed in event.
function addRequestDataToEvent
addRequestDataToEvent: ( event: Event, req: PolymorphicRequest, options?: AddRequestDataToEventOptions) => Event;
Add data from the given request to the given event
Parameter event
The event to which the request data will be added
Parameter req
Request object
Parameter
options.include Flags to control what data is included
Parameter
options.deps Injected platform-specific dependencies
Returns
The mutated
Event
objectDeprecated
Use
addNormalizedRequestDataToEvent
instead.
function addTracingExtensions
addTracingExtensions: () => void;
Deprecated
Use
registerSpanErrorInstrumentation()
instead. In v9, this function will be removed. Note that you don't need to call this in Node-based SDKs or when usingbrowserTracingIntegration
.
function addTracingHeadersToFetchRequest
addTracingHeadersToFetchRequest: ( request: string | unknown, _client: Client | undefined, _scope: Scope | undefined, fetchOptionsObj: { headers?: PolymorphicRequestHeaders | { [key: string]: string | string[] }; }, span?: Span) => PolymorphicRequestHeaders | undefined;
Adds sentry-trace and baggage headers to the various forms of fetch headers.
Deprecated
This function will not be exported anymore in v9.
function applyAggregateErrorsToEvent
applyAggregateErrorsToEvent: ( exceptionFromErrorImplementation: ( stackParser: StackParser, ex: Error ) => Exception, parser: StackParser, maxValueLimit: number | undefined, key: string, limit: number, event: Event, hint?: EventHint) => void;
Creates exceptions inside
event.exception.values
for errors that are nested on properties based on thekey
parameter.
function applyScopeDataToEvent
applyScopeDataToEvent: (event: Event, data: ScopeData) => void;
Applies data from the scope to the event and runs all event processors on it.
function applySdkMetadata
applySdkMetadata: ( options: Options, name: string, names?: string[], source?: string) => void;
A builder for the SDK metadata in the options for the SDK initialization.
Note: This function is identical to
buildMetadata
in Remix and NextJS and SvelteKit. We don't extract it for bundle size reasons.Parameter options
SDK options object that gets mutated
Parameter names
list of package names
See Also
https://github.com/getsentry/sentry-javascript/pull/7404
https://github.com/getsentry/sentry-javascript/pull/4196
If you make changes to this function consider updating the others as well.
function arrayify
arrayify: <T = unknown>(maybeArray: T | T[]) => T[];
Checks whether the given input is already an array, and if it isn't, wraps it in one.
Parameter maybeArray
Input to turn into an array, if necessary
Returns
The input, if already an array, or an array with the input as the only element, if not
Deprecated
This function has been deprecated and will not be replaced.
function baggageHeaderToDynamicSamplingContext
baggageHeaderToDynamicSamplingContext: ( baggageHeader: string | string[] | number | null | undefined | boolean) => Partial<DynamicSamplingContext> | undefined;
Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the "sentry-" prefixed values from it.
Parameter baggageHeader
A very bread definition of a baggage header as it might appear in various frameworks.
Returns
The Dynamic Sampling Context that was found on
baggageHeader
, if there was any,undefined
otherwise.
function basename
basename: (path: string, ext?: string) => string;
JSDoc
function callFrameToStackFrame
callFrameToStackFrame: ( frame: CallFrame, url: string | undefined, getModuleFromFilename: (filename: string | undefined) => string | undefined) => StackFrame;
Converts Debugger.CallFrame to Sentry StackFrame
function captureCheckIn
captureCheckIn: ( checkIn: CheckIn, upsertMonitorConfig?: MonitorConfig) => string;
Create a cron monitor check in and send it to Sentry.
Parameter checkIn
An object that describes a check in.
Parameter upsertMonitorConfig
An optional object that describes a monitor config. Use this if you want to create a monitor automatically when sending a check in.
function captureConsoleIntegration
captureConsoleIntegration: ( options?: CaptureConsoleOptions | undefined) => import('../types-hoist').Integration;
Send Console API calls as Sentry Events.
function captureEvent
captureEvent: (event: Event, hint?: EventHint) => string;
Captures a manually created event and sends it to Sentry.
Parameter event
The event to send to Sentry.
Parameter hint
Optional additional data to attach to the Sentry event.
Returns
the id of the captured event.
function captureException
captureException: ( exception: any, hint?: ExclusiveEventHintOrCaptureContext) => string;
Captures an exception event and sends it to Sentry.
Parameter exception
The exception to capture.
Parameter hint
Optional additional data to attach to the Sentry event.
Returns
the id of the captured Sentry event.
function captureFeedback
captureFeedback: ( params: SendFeedbackParams, hint?: EventHint & { includeReplay?: boolean }, scope?: import('./types-hoist').Scope) => string;
Send user feedback to Sentry.
function captureMessage
captureMessage: ( message: string, captureContext?: CaptureContext | SeverityLevel) => string;
Captures a message event and sends it to Sentry.
Parameter message
The message to send to Sentry.
Parameter captureContext
Define the level of the message or pass in additional data to attach to the message.
Returns
the id of the captured message.
function captureSession
captureSession: (end?: boolean) => void;
Sends the current session on the scope to Sentry
Parameter end
If set the session will be marked as exited and removed from the scope. Defaults to
false
.
function checkOrSetAlreadyCaught
checkOrSetAlreadyCaught: (exception: unknown) => boolean;
Checks whether or not we've already captured the given exception (note: not an identical exception - the very object in question), and marks it captured if not.
This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This function helps us ensure that even if we encounter the same error more than once, we only record it the first time we see it.
Note: It will ignore primitives (always return
false
and not mark them as seen), as properties can't be set on them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent object wrapper forms so that this check will always work. However, because we need to flag the exact object which will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification must be done before the exception captured.Parameter A
thrown exception to check or flag as having been seen
Returns
true
if the exception has already been captured,false
if not (with the side effect of marking it seen)
function close
close: (timeout?: number) => Promise<boolean>;
Call
close()
on the current client, if there is one. See Client.close.Parameter timeout
Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this parameter will cause the client to wait until all events are sent before disabling itself.
Returns
A promise which resolves to
true
if the queue successfully drains before the timeout, orfalse
if it doesn't (or if there's no client defined).
function closeSession
closeSession: (session: Session, status?: Exclude<SessionStatus, 'ok'>) => void;
Closes a session by setting its status and updating the session object with it. Internally calls
updateSession
to update the passed session object.Note that this function mutates the passed session (@see updateSession for explanation).
Parameter session
the
Session
object to be closedParameter status
the
SessionStatus
with which the session was closed. If you don't pass a status, this function will keep the previously set status, unless it was'ok'
in which case it is changed to'exited'
.
function consoleSandbox
consoleSandbox: <T>(callback: () => T) => T;
Temporarily disable sentry console instrumentations.
Parameter callback
The function to run against the original
console
messagesReturns
The results of the callback
function continueTrace
continueTrace: <V>( { sentryTrace, baggage, }: { sentryTrace: Parameters<typeof propagationContextFromHeaders>[0]; baggage: Parameters<typeof propagationContextFromHeaders>[1]; }, callback: () => V) => V;
Continue a trace from
sentry-trace
andbaggage
values. These values can be obtained from incoming request headers, or in the browser from<meta name="sentry-trace">
and<meta name="baggage">
HTML tags.Spans started with
startSpan
,startSpanManual
andstartInactiveSpan
, within the callback will automatically be attached to the incoming trace.
function convertToPlainObject
convertToPlainObject: <V>( value: V) => | V | { [ownProps: string]: unknown; type: string; target: string; currentTarget: string; detail?: unknown; } | { [ownProps: string]: unknown; message: string; name: string; stack?: string };
Transforms any
Error
orEvent
into a plain object with all of their enumerable properties, and some of their non-enumerable properties attached.Parameter value
Initial source that we have to transform in order for it to be usable by the serializer
Returns
An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor an Error.
function createAttachmentEnvelopeItem
createAttachmentEnvelopeItem: (attachment: Attachment) => AttachmentItem;
Creates attachment envelope items
function createCheckInEnvelope
createCheckInEnvelope: ( checkIn: SerializedCheckIn, dynamicSamplingContext?: Partial<DynamicSamplingContext>, metadata?: SdkMetadata, tunnel?: string, dsn?: DsnComponents) => CheckInEnvelope;
Create envelope from check in item.
function createClientReportEnvelope
createClientReportEnvelope: ( discarded_events: ClientReport['discarded_events'], dsn?: string, timestamp?: number) => ClientReportEnvelope;
Creates client report envelope
Parameter discarded_events
An array of discard events
Parameter dsn
A DSN that can be set on the header. Optional.
function createEnvelope
createEnvelope: <E extends Envelope>(headers: E[0], items?: E[1]) => E;
Creates an envelope. Make sure to always explicitly provide the generic to this function so that the envelope types resolve correctly.
function createEventEnvelope
createEventEnvelope: ( event: Event, dsn?: DsnComponents, metadata?: SdkMetadata, tunnel?: string) => EventEnvelope;
Create an Envelope from an event.
function createEventEnvelopeHeaders
createEventEnvelopeHeaders: ( event: Event, sdkInfo: SdkInfo | undefined, tunnel: string | undefined, dsn?: DsnComponents) => EventEnvelopeHeaders;
Creates event envelope headers, based on event, sdk info and tunnel Note: This function was extracted from the core package to make it available in Replay
function createSessionEnvelope
createSessionEnvelope: ( session: Session | SessionAggregates, dsn?: DsnComponents, metadata?: SdkMetadata, tunnel?: string) => SessionEnvelope;
Creates an envelope from a Session
function createSpanEnvelope
createSpanEnvelope: ( spans: [SentrySpan, ...SentrySpan[]], client?: Client) => SpanEnvelope;
Create envelope from Span item.
Takes an optional client and runs spans through
beforeSendSpan
if available.
function createSpanEnvelopeItem
createSpanEnvelopeItem: (spanJson: Partial<SpanJSON>) => SpanItem;
Creates envelope item for a single span
function createStackParser
createStackParser: (...parsers: StackLineParser[]) => StackParser;
Creates a stack parser with the supplied line parsers
StackFrames are returned in the correct order for Sentry Exception frames and with Sentry SDK internal frames removed from the top and bottom
function createTransport
createTransport: ( options: InternalBaseTransportOptions, makeRequest: TransportRequestExecutor, buffer?: PromiseBuffer<TransportMakeRequestResponse>) => Transport;
Creates an instance of a Sentry
Transport
Parameter options
Parameter makeRequest
function dateTimestampInSeconds
dateTimestampInSeconds: () => number;
Returns a timestamp in seconds since the UNIX epoch using the Date API.
TODO(v8): Return type should be rounded.
function debugIntegration
debugIntegration: ( options?: DebugOptions | undefined) => import('../types-hoist').Integration;
Integration to debug sent Sentry events. This integration should not be used in production.
Deprecated
This integration is deprecated and will be removed in the next major version of the SDK. To log outgoing events, use [Hook Options](https://docs.sentry.io/platforms/javascript/configuration/options/#hooks) (
beforeSend
,beforeSendTransaction
, ...).
function dedupeIntegration
dedupeIntegration: () => import('../types-hoist').Integration;
Deduplication filter.
function defineIntegration
defineIntegration: <Fn extends IntegrationFn<Integration>>( fn: Fn) => (...args: Parameters<Fn>) => Integration;
Define an integration function that can be used to create an integration instance. Note that this by design hides the implementation details of the integration, as they are considered internal.
function dirname
dirname: (path: string) => string;
JSDoc
function disabledUntil
disabledUntil: (limits: RateLimits, dataCategory: DataCategory) => number;
Gets the time that the given category is disabled until for rate limiting. In case no category-specific limit is set but a general rate limit across all categories is active, that time is returned.
the time in ms that the category is disabled until or 0 if there's no active rate limit.
function dropUndefinedKeys
dropUndefinedKeys: <T>(inputValue: T) => T;
Given any object, return a new object having removed all fields whose value was
undefined
. Works recursively on objects and arrays.Attention: This function keeps circular references in the returned object.
function dsnFromString
dsnFromString: (str: string) => DsnComponents | undefined;
Parses a Dsn from a given string.
Parameter str
A Dsn as string
Parameter str
is not a valid DSN string
Returns
Dsn as DsnComponents or undefined if
function dsnToString
dsnToString: (dsn: DsnComponents, withPassword?: boolean) => string;
Renders the string representation of this Dsn.
By default, this will render the public representation without the password component. To get the deprecated private representation, set
withPassword
to true.Parameter withPassword
When set to true, the password will be included.
function dynamicRequire
dynamicRequire: (mod: any, request: string) => any;
Requires a module which is protected against bundler minification.
Parameter request
The module path to resolve
Deprecated
This function will be removed in the next major version.
function dynamicSamplingContextToSentryBaggageHeader
dynamicSamplingContextToSentryBaggageHeader: ( dynamicSamplingContext?: Partial<DynamicSamplingContext>) => string | undefined;
Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with "sentry-".
Parameter dynamicSamplingContext
The Dynamic Sampling Context to turn into a header. For convenience and compatibility with the
getDynamicSamplingContext
method on the Transaction class ,this argument can also beundefined
. If it isundefined
the function will returnundefined
.Returns
a baggage header, created from
dynamicSamplingContext
, orundefined
either ifdynamicSamplingContext
wasundefined
, or ifdynamicSamplingContext
didn't contain any values.
function endSession
endSession: () => void;
End the session on the current isolation scope.
function envelopeContainsItemType
envelopeContainsItemType: ( envelope: Envelope, types: EnvelopeItemType[]) => boolean;
Returns true if the envelope contains any of the given envelope item types
function envelopeItemTypeToDataCategory
envelopeItemTypeToDataCategory: (type: EnvelopeItemType) => DataCategory;
Maps the type of an envelope item to a data category.
function escapeStringForRegex
escapeStringForRegex: (regexString: string) => string;
Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to
new RegExp()
.Parameter regexString
The string to escape
Returns
An version of the string with all special regex characters escaped
function eventFromMessage
eventFromMessage: ( stackParser: StackParser, message: ParameterizedString, level?: SeverityLevel, hint?: EventHint, attachStacktrace?: boolean) => Event;
Builds and Event from a Message
function eventFromUnknownInput
eventFromUnknownInput: ( client: Client, stackParser: StackParser, exception: unknown, hint?: EventHint) => Event;
Builds and Event from a Exception
function exceptionFromError
exceptionFromError: (stackParser: StackParser, error: Error) => Exception;
Extracts stack frames from the error and builds a Sentry Exception
function extractExceptionKeysForMessage
extractExceptionKeysForMessage: ( exception: Record<string, unknown>, maxLength?: number) => string;
Given any captured exception, extract its keys and create a sorted and truncated list that will be used inside the event message. eg.
Non-error exception captured with keys: foo, bar, baz
function extractPathForTransaction
extractPathForTransaction: ( req: PolymorphicRequest, options?: { path?: boolean; method?: boolean; customRoute?: string }) => [string, TransactionSource];
Extracts a complete and parameterized path from the request object and uses it to construct transaction name. If the parameterized transaction name cannot be extracted, we fall back to the raw URL.
Additionally, this function determines and returns the transaction name source
eg. GET /mountpoint/user/:id
Parameter req
A request object
Parameter options
What to include in the transaction name (method, path, or a custom route name to be used instead of the request's route)
Returns
A tuple of the fully constructed transaction name [0] and its source [1] (can be either 'route' or 'url')
Deprecated
This method will be removed in v9. It is not in use anymore.
function extractQueryParamsFromUrl
extractQueryParamsFromUrl: (url: string) => string | undefined;
Extract the query params from an URL.
function extractRequestData
extractRequestData: ( req: PolymorphicRequest, options?: { include?: string[] }) => ExtractedNodeRequestData;
Normalize data from the request object, accounting for framework differences.
Parameter req
The request object from which to extract data
Parameter
options.include An optional array of keys to include in the normalized data. Defaults to DEFAULT_REQUEST_INCLUDES if not provided.
Parameter
options.deps Injected, platform-specific dependencies
Returns
An object containing normalized request data
Deprecated
Instead manually normalize the request data into a format that fits
addNormalizedRequestDataToEvent
.
function extractTraceparentData
extractTraceparentData: (traceparent?: string) => TraceparentData | undefined;
Extract transaction context data from a
sentry-trace
header.Parameter traceparent
Traceparent string
Returns
Object containing data from the header, or undefined if traceparent string is malformed
function extraErrorDataIntegration
extraErrorDataIntegration: ( options?: Partial<ExtraErrorDataOptions> | undefined) => import('../types-hoist').Integration;
function filenameIsInApp
filenameIsInApp: (filename: string, isNative?: boolean) => boolean;
Does this filename look like it's part of the app code?
function fill
fill: ( source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any) => void;
Replace a method in an object with a wrapped version of itself.
Parameter source
An object that contains a method to be wrapped.
Parameter name
The name of the method to be wrapped.
Parameter replacementFactory
A higher-order function that takes the original version of the given method and returns a wrapped version. Note: The function returned by
replacementFactory
needs to be a non-arrow function, in order to preserve the correct value ofthis
, and the original method must be called using `origMethod.call(this, <other args>)or
origMethod.apply(this, [<other args>])(rather than being called directly), again to preserve
this`.Returns
void
function flatten
flatten: <T>(input: NestedArray<T>) => T[];
Flattens a multi-dimensional array
Deprecated
This function is deprecated and will be removed in the next major version.
function flush
flush: (timeout?: number) => Promise<boolean>;
Call
flush()
on the current client, if there is one. See Client.flush.Parameter timeout
Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause the client to wait until all events are sent before resolving the promise.
Returns
A promise which resolves to
true
if the queue successfully drains before the timeout, orfalse
if it doesn't (or if there's no client defined).
function forEachEnvelopeItem
forEachEnvelopeItem: <E extends Envelope>( envelope: Envelope, callback: ( envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type'] ) => boolean | void) => boolean;
Convenience function to loop through the items and item types of an envelope. (This function was mostly created because working with envelope types is painful at the moment)
If the callback returns true, the rest of the items will be skipped.
function functionToStringIntegration
functionToStringIntegration: () => import('../types-hoist').Integration;
Patch toString calls to return proper name for wrapped functions.
Sentry.init({integrations: [functionToStringIntegration(),],});
function generatePropagationContext
generatePropagationContext: () => PropagationContext;
Returns a new minimal propagation context.
Deprecated
Use
generateTraceId
andgenerateSpanId
instead.
function generateSentryTraceHeader
generateSentryTraceHeader: ( traceId?: string, spanId?: string, sampled?: boolean) => string;
Create sentry-trace header from span context values.
function generateSpanId
generateSpanId: () => string;
Generate a random, valid span ID.
function generateTraceId
generateTraceId: () => string;
Generate a random, valid trace ID.
function getActiveSpan
getActiveSpan: () => Span | undefined;
Returns the currently active span.
function getBreadcrumbLogLevelFromHttpStatusCode
getBreadcrumbLogLevelFromHttpStatusCode: ( statusCode: number | undefined) => SeverityLevel | undefined;
Determine a breadcrumb's log level (only
warning
orerror
) based on an HTTP status code.
function getCapturedScopesOnSpan
getCapturedScopesOnSpan: (span: Span) => { scope?: Scope; isolationScope?: Scope;};
Grabs the scope and isolation scope off a span that were active when the span was started.
function getClient
getClient: <C extends Client<ClientOptions<BaseTransportOptions>>>() => | C | undefined;
Get the currently active client.
function getComponentName
getComponentName: (elem: unknown) => string | null;
Given a DOM element, traverses up the tree until it finds the first ancestor node that has the
data-sentry-component
ordata-sentry-element
attribute withdata-sentry-component
taking precedence. This attribute is added at build-time by projects that have the component name annotation plugin installed.Returns
a string representation of the component for the provided DOM element, or
null
if not found
function getCurrentHubShim
getCurrentHubShim: () => Hub;
This is for legacy reasons, and returns a proxy object instead of a hub to be used.
Deprecated
Use the methods directly from the top level Sentry API (e.g.
Sentry.withScope
) For more information see our migration guide for [replacinggetCurrentHub
andHub
](https://github.com/getsentry/sentry-javascript/blob/develop/MIGRATION.md#deprecate-hub) usage
function getCurrentScope
getCurrentScope: () => Scope;
Get the currently active scope.
function getDebugImagesForResources
getDebugImagesForResources: ( stackParser: StackParser, resource_paths: ReadonlyArray<string>) => DebugImage[];
Returns a list of debug images for the given resources.
function getDefaultCurrentScope
getDefaultCurrentScope: () => Scope;
Get the default current scope.
function getDefaultIsolationScope
getDefaultIsolationScope: () => Scope;
Get the default isolation scope.
function getDomElement
getDomElement: <E = any>(selector: string) => E | null;
Gets a DOM element by using document.querySelector.
This wrapper will first check for the existence of the function before actually calling it so that we don't have to take care of this check, every time we want to access the DOM.
Reason: DOM/querySelector is not available in all environments.
We have to cast to any because utils can be consumed by a variety of environments, and we don't want to break TS users. If you know what element will be selected by
document.querySelector
, specify it as part of the generic call. For example,const element = getDomElement<Element>('selector');
Parameter selector
the selector string passed on to document.querySelector
function getDynamicSamplingContextFromClient
getDynamicSamplingContextFromClient: ( trace_id: string, client: Client) => DynamicSamplingContext;
Creates a dynamic sampling context from a client.
Dispatches the
createDsc
lifecycle hook as a side effect.
function getDynamicSamplingContextFromScope
getDynamicSamplingContextFromScope: ( client: Client, scope: Scope) => Partial<DynamicSamplingContext>;
Get the dynamic sampling context for the currently active scopes.
function getDynamicSamplingContextFromSpan
getDynamicSamplingContextFromSpan: ( span: Span) => Readonly<Partial<DynamicSamplingContext>>;
Creates a dynamic sampling context from a span (and client and scope)
Parameter span
the span from which a few values like the root span name and sample rate are extracted.
Returns
a dynamic sampling context
function getEnvelopeEndpointWithUrlEncodedAuth
getEnvelopeEndpointWithUrlEncodedAuth: ( dsn: DsnComponents, tunnel?: string, sdkInfo?: SdkInfo) => string;
Returns the envelope endpoint URL with auth in the query string.
Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
function getEventDescription
getEventDescription: (event: Event) => string;
Extracts either message or type+value from an event that can be used for user-facing logs
Returns
event's description
function getFilenameToDebugIdMap
getFilenameToDebugIdMap: (stackParser: StackParser) => Record<string, string>;
Returns a map of filenames to debug identifiers.
function getFramesFromEvent
getFramesFromEvent: (event: Event) => StackFrame[] | undefined;
Get's stack frames from an event without needing to check for undefined properties.
function getFunctionName
getFunctionName: (fn: unknown) => string;
Safely extract function name from itself
function getGlobalScope
getGlobalScope: () => Scope;
Get the global scope. This scope is applied to _all_ events.
function getGlobalSingleton
getGlobalSingleton: <T>( name: keyof SentryCarrier, creator: () => T, obj?: unknown) => T;
Returns a global singleton contained in the global
__SENTRY__[]
object.If the singleton doesn't already exist in
__SENTRY__
, it will be created using the given factory function and added to the__SENTRY__
object.Parameter name
name of the global singleton on __SENTRY__
Parameter creator
creator Factory function to create the singleton if it doesn't already exist on
__SENTRY__
Parameter obj
(Optional) The global object on which to look for
__SENTRY__
, if notGLOBAL_OBJ
's return valueReturns
the singleton
function getIntegrationsToSetup
getIntegrationsToSetup: ( options: Pick<Options, 'defaultIntegrations' | 'integrations'>) => Integration[];
Gets integrations to install
function getIsolationScope
getIsolationScope: () => Scope;
Get the currently active isolation scope. The isolation scope is active for the current execution context.
function getLocationHref
getLocationHref: () => string;
A safe form of location.href
function getMainCarrier
getMainCarrier: () => Carrier;
Returns the global shim registry.
FIXME: This function is problematic, because despite always returning a valid Carrier, it has an optional
__SENTRY__
property, which then in turn requires us to always perform an unnecessary check at the call-site. We always access the carrier through this function, so we can guarantee that__SENTRY__
is there.
function getMetricSummaryJsonForSpan
getMetricSummaryJsonForSpan: ( span: Span) => Record<string, Array<MetricSummary>> | undefined;
Fetches the metric summary if it exists for the passed span
function getNumberOfUrlSegments
getNumberOfUrlSegments: (url: string) => number;
Returns number of URL segments of a passed string URL.
Deprecated
This function will be removed in the next major version.
function getOriginalFunction
getOriginalFunction: <T extends Function>( func: WrappedFunction<T>) => T | undefined;
This extracts the original function if available. See
markFunctionWrapped
for more information.Parameter func
the function to unwrap
Returns
the unwrapped version of the function if available.
function getReportDialogEndpoint
getReportDialogEndpoint: ( dsnLike: DsnLike, dialogOptions: { [key: string]: any; user?: { name?: string; email?: string } }) => string;
Returns the url to the report dialog endpoint.
function getRootSpan
getRootSpan: (span: SpanWithPotentialChildren) => Span;
Returns the root span of a given span.
function getSanitizedUrlString
getSanitizedUrlString: (url: PartialURL) => string;
Takes a URL object and returns a sanitized string which is safe to use as span name see: https://develop.sentry.dev/sdk/data-handling/#structuring-data
function getSdkMetadataForEnvelopeHeader
getSdkMetadataForEnvelopeHeader: ( metadataOrEvent?: SdkMetadata | Event) => SdkInfo | undefined;
Extracts the minimal SDK info from the metadata or an events
function getSDKSource
getSDKSource: () => SdkSource;
Get source of SDK.
function getSpanDescendants
getSpanDescendants: (span: SpanWithPotentialChildren) => Span[];
Returns an array of the given span and all of its descendants.
function getSpanStatusFromHttpCode
getSpanStatusFromHttpCode: (httpStatus: number) => SpanStatus;
Converts a HTTP status code into a sentry status with a message.
Parameter httpStatus
The HTTP response status code.
Returns
The span status or unknown_error.
function getStatusMessage
getStatusMessage: (status: SpanStatus | undefined) => string | undefined;
Get the status message to use for a JSON representation of a span.
function getTraceContextFromScope
getTraceContextFromScope: (scope: Scope) => TraceContext;
Get a trace context for the given scope.
function getTraceData
getTraceData: (options?: { span?: Span }) => SerializedTraceData;
Extracts trace propagation data from the current span or from the client's scope (via transaction or propagation context) and serializes it to
sentry-trace
andbaggage
values to strings. These values can be used to propagate a trace via our tracing Http headers or Html<meta>
tags.This function also applies some validation to the generated sentry-trace and baggage values to ensure that only valid strings are returned.
Returns
an object with the tracing data values. The object keys are the name of the tracing key to be used as header or meta tag name.
function getTraceMetaTags
getTraceMetaTags: () => string;
Returns a string of meta tags that represent the current trace data.
You can use this to propagate a trace from your server-side rendered Html to the browser. This function returns up to two meta tags,
sentry-trace
andbaggage
, depending on the current trace data state.Example 1
Usage example:
function renderHtml() {return `<head>${getTraceMetaTags()}</head>`;}
function handleCallbackErrors
handleCallbackErrors: <Fn extends () => any>( fn: Fn, onError: (error: unknown) => void, onFinally?: () => void) => ReturnType<Fn>;
Wrap a callback function with error handling. If an error is thrown, it will be passed to the
onError
callback and re-thrown.If the return value of the function is a promise, it will be handled with
maybeHandlePromiseRejection
.If an
onFinally
callback is provided, this will be called when the callback has finished - so if it returns a promise, once the promise resolved/rejected, else once the callback has finished executing. TheonFinally
callback will _always_ be called, no matter if an error was thrown or not.
function hasTracingEnabled
hasTracingEnabled: ( maybeOptions?: | Pick<Options, 'tracesSampleRate' | 'tracesSampler' | 'enableTracing'> | undefined) => boolean;
Determines if tracing is currently enabled.
Tracing is enabled when at least one of
tracesSampleRate
andtracesSampler
is defined in the SDK config.
function headersToDict
headersToDict: ( reqHeaders: Record<string, string | string[] | undefined>) => Record<string, string>;
Convert common request headers to a simple dictionary.
function htmlTreeAsString
htmlTreeAsString: ( elem: unknown, options?: string[] | { keyAttrs?: string[]; maxStringLength?: number }) => string;
Given a child DOM element, returns a query-selector statement describing that and its ancestors e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
Returns
generated DOM path
function httpRequestToRequestData
httpRequestToRequestData: (request: { method?: string; url?: string; headers?: { [key: string]: string | string[] }; protocol?: string; socket?: unknown;}) => RequestEventData;
Convert a HTTP request object to RequestEventData to be passed as normalizedRequest. Instead of allowing
PolymorphicRequest
to be passed, we want to be more specific and generally require a http.IncomingMessage-like object.
function inboundFiltersIntegration
inboundFiltersIntegration: ( options?: Partial<InboundFiltersOptions> | undefined) => import('../types-hoist').Integration;
function initAndBind
initAndBind: < F extends Client<ClientOptions<BaseTransportOptions>>, O extends ClientOptions<BaseTransportOptions>>( clientClass: ClientClass<F, O>, options: O) => Client;
Internal function to create a new SDK client instance. The client is installed and then bound to the current scope.
Parameter clientClass
The client class to instantiate.
Parameter options
Options to pass to the client.
function instrumentFetchRequest
instrumentFetchRequest: ( handlerData: HandlerDataFetch, shouldCreateSpan: (url: string) => boolean, shouldAttachHeaders: (url: string) => boolean, spans: Record<string, Span>, spanOrigin?: SpanOrigin) => Span | undefined;
Create and track fetch request spans for usage in combination with
addFetchInstrumentationHandler
.Returns
Span if a span was created, otherwise void.
function isAbsolute
isAbsolute: (path: string) => boolean;
JSDoc
function isBrowser
isBrowser: () => boolean;
Returns true if we are in the browser.
function isBrowserBundle
isBrowserBundle: () => boolean;
Figures out if we're building a browser bundle.
Returns
true if this is a browser bundle build.
function isDOMError
isDOMError: (wat: unknown) => boolean;
Checks whether given value's type is DOMError isDOMError.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isDOMException
isDOMException: (wat: unknown) => boolean;
Checks whether given value's type is DOMException isDOMException.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isElement
isElement: (wat: unknown) => boolean;
Checks whether given value's type is an Element instance isElement.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isEnabled
isEnabled: () => boolean;
If the SDK is initialized & enabled.
function isError
isError: (wat: unknown) => wat is Error;
Checks whether given value's type is one of a few Error or Error-like isError.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isErrorEvent
isErrorEvent: (wat: unknown) => boolean;
Checks whether given value's type is ErrorEvent isErrorEvent.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isEvent
isEvent: (wat: unknown) => wat is PolymorphicEvent;
Checks whether given value's type is an Event instance isEvent.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isInitialized
isInitialized: () => boolean;
Returns true if Sentry has been properly initialized.
function isInstanceOf
isInstanceOf: (wat: any, base: any) => boolean;
Checks whether given value's type is an instance of provided constructor. isInstanceOf.
Parameter wat
A value to be checked.
Parameter base
A constructor to be used in a check.
Returns
A boolean representing the result.
function isMatchingPattern
isMatchingPattern: ( value: string, pattern: RegExp | string, requireExactStringMatch?: boolean) => boolean;
Checks if the given value matches a regex or string
Parameter value
The string to test
Parameter pattern
Either a regex or a string against which
value
will be matchedParameter requireExactStringMatch
If true,
value
must matchpattern
exactly. If false,value
will matchpattern
if it containspattern
. Only applies to string-type patterns.
function isNativeFunction
isNativeFunction: (func: Function) => boolean;
isNative checks if the given function is a native implementation
function isNodeEnv
isNodeEnv: () => boolean;
Checks whether we're in the Node.js or Browser environment
Returns
Answer to given question
function isParameterizedString
isParameterizedString: (wat: unknown) => wat is ParameterizedString;
Checks whether given string is parameterized isParameterizedString.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isPlainObject
isPlainObject: (wat: unknown) => wat is Record<string, unknown>;
Checks whether given value's type is an object literal, or a class instance. isPlainObject.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isPrimitive
isPrimitive: (wat: unknown) => wat is Primitive;
Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol) isPrimitive.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isRateLimited
isRateLimited: ( limits: RateLimits, dataCategory: DataCategory, now?: number) => boolean;
Checks if a category is rate limited
function isRegExp
isRegExp: (wat: unknown) => wat is RegExp;
Checks whether given value's type is an regexp isRegExp.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isSentryRequestUrl
isSentryRequestUrl: (url: string, client: Client | undefined) => boolean;
Checks whether given url points to Sentry server
Parameter url
url to verify
function isString
isString: (wat: unknown) => wat is string;
Checks whether given value's type is a string isString.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isSyntheticEvent
isSyntheticEvent: (wat: unknown) => boolean;
Checks whether given value's type is a SyntheticEvent isSyntheticEvent.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function isThenable
isThenable: (wat: any) => wat is PromiseLike<any>;
Checks whether given value has a then function.
Parameter wat
A value to be checked.
function isVueViewModel
isVueViewModel: (wat: unknown) => boolean;
Checks whether given value's type is a Vue ViewModel.
Parameter wat
A value to be checked.
Returns
A boolean representing the result.
function join
join: (...args: string[]) => string;
JSDoc
function lastEventId
lastEventId: () => string | undefined;
The last error event id of the isolation scope.
Warning: This function really returns the last recorded error event id on the current isolation scope. If you call this function after handling a certain error and another error is captured in between, the last one is returned instead of the one you might expect. Also, ids of events that were never sent to Sentry (for example because they were dropped in
beforeSend
) could be returned.Returns
The last event id of the isolation scope.
function linkedErrorsIntegration
linkedErrorsIntegration: ( options?: LinkedErrorsOptions | undefined) => import('../types-hoist').Integration;
function loadModule
loadModule: <T>(moduleName: string) => T | undefined;
Helper for dynamically loading module that should work with linked dependencies. The problem is that we _should_ be using
require(require.resolve(moduleName, { paths: [cwd()] }))
However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during build time.require.resolve
is also not available in any other way, so we cannot create, a fake helper like we do withdynamicRequire
.We always prefer to use local package, thus the value is not returned early from each
try/catch
block. That is to mimic the behavior ofrequire.resolve
exactly.Parameter moduleName
module name to require
Returns
possibly required module
function logSpanEnd
logSpanEnd: (span: Span) => void;
Print a log message for an ended span.
function logSpanStart
logSpanStart: (span: Span) => void;
Print a log message for a started span.
function makeDsn
makeDsn: (from: DsnLike) => DsnComponents | undefined;
Creates a valid Sentry Dsn object, identifying a Sentry instance and project.
Parameter from
is an invalid DSN source
Returns
a valid DsnComponents object or
undefined
if
function makeFifoCache
makeFifoCache: <Key extends string, Value>( size: number) => { get: (key: Key) => Value | undefined; add: (key: Key, value: Value) => void; delete: (key: Key) => boolean; clear: () => void; size: () => number;};
Creates a cache that evicts keys in fifo order
Parameter size
Deprecated
This function is deprecated and will be removed in the next major version.
function makeMultiplexedTransport
makeMultiplexedTransport: <TO extends BaseTransportOptions>( createTransport: (options: TO) => Transport, matcher: Matcher) => (options: TO) => Transport;
Creates a transport that can send events to different DSNs depending on the envelope contents.
function makeOfflineTransport
makeOfflineTransport: <TO>( createTransport: (options: TO) => Transport) => (options: TO & OfflineTransportOptions) => Transport;
Wraps a transport and stores and retries events when they fail to send.
Parameter createTransport
The transport to wrap.
function makePromiseBuffer
makePromiseBuffer: <T>(limit?: number) => PromiseBuffer<T>;
Creates an new PromiseBuffer object with the specified limit
Parameter limit
max number of promises that can be stored in the buffer
function makeSession
makeSession: (context?: Omit<SessionContext, 'started' | 'status'>) => Session;
Creates a new
Session
object by setting certain default parameters. If optionalParameter context
is passed, the passed properties are applied to the session object.
Parameter context
(optional) additional properties to be applied to the returned session object
Returns
a new
Session
object
function markFunctionWrapped
markFunctionWrapped: ( wrapped: WrappedFunction, original: WrappedFunction) => void;
Remembers the original function on the wrapped function and patches up the prototype.
Parameter wrapped
the wrapper function
Parameter original
the original function that gets wrapped
function maybeInstrument
maybeInstrument: (type: InstrumentHandlerType, instrumentFn: () => void) => void;
Maybe run an instrumentation function, unless it was already called.
function memoBuilder
memoBuilder: () => MemoFunc;
Helper to decycle json objects
Deprecated
This function is deprecated and will be removed in the next major version.
function mergeScopeData
mergeScopeData: (data: ScopeData, mergeData: ScopeData) => void;
Merge data of two scopes together.
function moduleMetadataIntegration
moduleMetadataIntegration: () => import('../types-hoist').Integration;
Adds module metadata to stack frames.
Metadata can be injected by the Sentry bundler plugins using the
moduleMetadata
config option.When this integration is added, the metadata passed to the bundler plugin is added to the stack frames of all events under the
module_metadata
property. This can be used to help in tagging or routing of events from different teams our sources
function node
node: (getModule?: GetModuleFn) => StackLineParserFn;
Node Stack line parser
function nodeStackLineParser
nodeStackLineParser: (getModule?: GetModuleFn) => StackLineParser;
Node.js stack line parser
This is in @sentry/core so it can be used from the Electron SDK in the browser for when
nodeIntegration == true
. This allows it to be used without referencing or importing any node specific code which causes bundlers to complain
function normalize
normalize: (input: unknown, depth?: number, maxProperties?: number) => any;
Recursively normalizes the given object.
- Creates a copy to prevent original input mutation - Skips non-enumerable properties - When stringifying, calls
toJSON
if implemented - Removes circular references - Translates non-serializable values (undefined
/NaN
/functions) to serializable format - Translates known global objects/classes to a string representations - Takes care ofError
object serialization - Optionally limits depth of final output - Optionally limits number of properties/elements included in any single object/arrayParameter input
The object to be normalized.
Parameter depth
The max depth to which to normalize the object. (Anything deeper stringified whole.)
Parameter maxProperties
The max number of elements or properties to be included in any single array or object in the normalized output.
Returns
A normalized version of the object, or
"**non-serializable**"
if any errors are thrown during normalization.
function normalizePath
normalizePath: (path: string) => string;
JSDoc
function normalizeToSize
normalizeToSize: <T>( object: { [key: string]: any }, depth?: number, maxSize?: number) => T;
JSDoc
function normalizeUrlToBase
normalizeUrlToBase: (url: string, basePath: string) => string;
Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint across platforms and working directory.
Parameter url
The URL to be normalized.
Parameter basePath
The application base path.
Returns
The normalized URL.
function notifyEventProcessors
notifyEventProcessors: ( processors: EventProcessor[], event: Event | null, hint: EventHint, index?: number) => PromiseLike<Event | null>;
Process an array of event processors, returning the processed event (or
null
if the event was dropped).
function objectify
objectify: (wat: unknown) => typeof Object;
Ensure that something is an object.
Turns
undefined
andnull
intoString
s and all other primitives into instances of their respective wrapper classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.Parameter wat
The subject of the objectification
Returns
A version of
wat
which can safely be used withObject
class methods
function parameterize
parameterize: ( strings: TemplateStringsArray, ...values: string[]) => ParameterizedString;
Tagged template function which returns parameterized representation of the message For example: parameterize
This is a log statement with ${x} and ${y} params
, would return: "__sentry_template_string__": 'This is a log statement with %s and %s params', "__sentry_template_values__": ['first', 'second']Parameter strings
An array of string values splitted between expressions
Parameter values
Expressions extracted from template string
Returns
String with template information in __sentry_template_string__ and __sentry_template_values__ properties
function parseBaggageHeader
parseBaggageHeader: ( baggageHeader: string | string[] | number | null | undefined | boolean) => Record<string, string> | undefined;
Take a baggage header and parse it into an object.
function parseEnvelope
parseEnvelope: (env: string | Uint8Array) => Envelope;
Parses an envelope
function parseRetryAfterHeader
parseRetryAfterHeader: (header: string, now?: number) => number;
Extracts Retry-After value from the request header or returns default value
Parameter header
string representation of 'Retry-After' header
Parameter now
current unix timestamp
function parseSampleRate
parseSampleRate: (sampleRate: unknown) => number | undefined;
Parse a sample rate from a given value. This will either return a boolean or number sample rate, if the sample rate is valid (between 0 and 1). If a string is passed, we try to convert it to a number.
Any invalid sample rate will return
undefined
.
function parseSemver
parseSemver: (input: string) => SemVer;
Parses input into a SemVer interface
Parameter input
string representation of a semver version
function parseStackFrames
parseStackFrames: (stackParser: StackParser, error: Error) => StackFrame[];
Extracts stack frames from the error.stack string
function parseUrl
parseUrl: (url: string) => PartialURL;
Parses string form of URL into an object // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B // intentionally using regex and not href parsing trick because React Native and other // environments where DOM might not be available
Returns
parsed URL object
function prepareEvent
prepareEvent: ( options: ClientOptions, event: Event, hint: EventHint, scope?: ScopeInterface, client?: Client, isolationScope?: ScopeInterface) => PromiseLike<Event | null>;
Adds common information to events.
The information includes release and environment from
options
, breadcrumbs and context (extra, tags and user) from the scope.Information that is already present in the event is never overwritten. For nested objects, such as the context, keys are merged.
Parameter event
The original event.
Parameter hint
May contain additional information about the original exception.
Parameter scope
A scope containing event metadata.
Returns
A new event with more information.
function propagationContextFromHeaders
propagationContextFromHeaders: ( sentryTrace: string | undefined, baggage: string | number | boolean | string[] | null | undefined) => PropagationContext;
Create a propagation context from incoming headers or creates a minimal new one if the headers are undefined.
function registerSpanErrorInstrumentation
registerSpanErrorInstrumentation: () => void;
Ensure that global errors automatically set the active span status.
function rejectedSyncPromise
rejectedSyncPromise: <T = never>(reason?: any) => PromiseLike<T>;
Creates a rejected sync promise.
Parameter value
the value to reject the promise with
Returns
the rejected sync promise
function relative
relative: (from: string, to: string) => string;
JSDoc
function requestDataIntegration
requestDataIntegration: ( options?: RequestDataIntegrationOptions | undefined) => import('../types-hoist').Integration;
Add data about a request to an event. Primarily for use in Node-based SDKs, but included in
@sentry/core
so it can be used in cross-platform SDKs like@sentry/nextjs
.
function resetInstrumentationHandlers
resetInstrumentationHandlers: () => void;
Reset all instrumentation handlers. This can be used by tests to ensure we have a clean slate of instrumentation handlers.
function resolve
resolve: (...args: string[]) => string;
JSDoc
function resolvedSyncPromise
resolvedSyncPromise: { (): PromiseLike<void>; <T>(value: T | PromiseLike<T>): PromiseLike<T>;};
function rewriteFramesIntegration
rewriteFramesIntegration: ( options?: RewriteFramesOptions | undefined) => import('../types-hoist').Integration;
Rewrite event frames paths.
function safeJoin
safeJoin: (input: any[], delimiter?: string) => string;
Join values in array
Parameter input
array of values to be joined together
Parameter delimiter
string to be placed in-between values
Returns
Joined values
function sampleSpan
sampleSpan: ( options: Pick<Options, 'tracesSampleRate' | 'tracesSampler' | 'enableTracing'>, samplingContext: SamplingContext) => [sampled: boolean, sampleRate?: number];
Makes a sampling decision for the given options.
Called every time a root span is created. Only root spans which emerge with a
sampled
value oftrue
will be sent to Sentry.
function serializeEnvelope
serializeEnvelope: (envelope: Envelope) => string | Uint8Array;
Serializes an envelope.
function sessionTimingIntegration
sessionTimingIntegration: () => import('../types-hoist').Integration;
This function adds duration since the sessionTimingIntegration was initialized till the time event was sent.
Deprecated
This integration is deprecated and will be removed in the next major version of the SDK. To capture session durations alongside events, use [Context](https://docs.sentry.io/platforms/javascript/enriching-events/context/) (
Sentry.setContext()
).
function setAsyncContextStrategy
setAsyncContextStrategy: (strategy: AsyncContextStrategy | undefined) => void;
Private API with no semver guarantees!
Sets the global async context strategy
function setCapturedScopesOnSpan
setCapturedScopesOnSpan: ( span: Span | undefined, scope: Scope, isolationScope: Scope) => void;
Store the scope & isolation scope for a span, which can the be used when it is finished.
function setContext
setContext: (name: string, context: { [key: string]: any }) => void;
Sets context data with the given name.
Parameter name
of the context
Parameter context
Any kind of data. This data will be normalized.
function setCurrentClient
setCurrentClient: (client: Client) => void;
Make the given client the current client.
function setExtra
setExtra: (key: string, extra: Extra) => void;
Set key:value that will be sent as extra data with the event.
Parameter key
String of extra
Parameter extra
Any kind of data. This data will be normalized.
function setExtras
setExtras: (extras: Extras) => void;
Set an object that will be merged sent as extra data with the event.
Parameter extras
Extras object to merge into current context.
function setHttpStatus
setHttpStatus: (span: Span, httpStatus: number) => void;
Sets the Http status attributes on the current span based on the http code. Additionally, the span's status is updated, depending on the http code.
function setMeasurement
setMeasurement: ( name: string, value: number, unit: MeasurementUnit, activeSpan?: import('../types-hoist').Span | undefined) => void;
Adds a measurement to the active transaction on the current global scope. You can optionally pass in a different span as the 4th parameter.
function setTag
setTag: (key: string, value: Primitive) => void;
Set key:value that will be sent as tags data with the event.
Can also be used to unset a tag, by passing
undefined
.Parameter key
String key of tag
Parameter value
Value of tag
function setTags
setTags: (tags: { [key: string]: Primitive }) => void;
Set an object that will be merged sent as tags data with the event.
Parameter tags
Tags context object to merge into current context.
function setUser
setUser: (user: User | null) => void;
Updates user context information for future events.
Parameter user
User context object to be set in the current context. Pass
null
to unset the user.
function severityLevelFromString
severityLevelFromString: (level: SeverityLevel | string) => SeverityLevel;
Converts a string-based level into a
SeverityLevel
, normalizing it along the way.Parameter level
String representation of desired
SeverityLevel
.Returns
The
SeverityLevel
corresponding to the given string, or 'log' if the string isn't a valid level.
function snipLine
snipLine: (line: string, colno: number) => string;
This is basically just
trim_line
from https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67Parameter str
An object that contains serializable values
Parameter max
Maximum number of characters in truncated string
Returns
string Encoded
function spanIsSampled
spanIsSampled: (span: Span) => boolean;
Returns true if a span is sampled. In most cases, you should just use
span.isRecording()
instead. However, this has a slightly different semantic, as it also returns false if the span is finished. So in the case where this distinction is important, use this method.
function spanTimeInputToSeconds
spanTimeInputToSeconds: (input: SpanTimeInput | undefined) => number;
Convert a span time input into a timestamp in seconds.
function spanToBaggageHeader
spanToBaggageHeader: (span: Span) => string | undefined;
Convert a Span to a baggage header.
function spanToJSON
spanToJSON: (span: Span) => Partial<SpanJSON>;
Convert a span to a JSON representation.
function spanToTraceContext
spanToTraceContext: (span: Span) => TraceContext;
Convert a span to a trace context, which can be sent as the
trace
context in a non-transaction event.
function spanToTraceHeader
spanToTraceHeader: (span: Span) => string;
Convert a Span to a Sentry trace header.
function stackParserFromStackParserOptions
stackParserFromStackParserOptions: ( stackParser: StackParser | StackLineParser[]) => StackParser;
Gets a stack parser implementation from Options.stackParser
See Also
Options
If options contains an array of line parsers, it is converted into a parser
function startIdleSpan
startIdleSpan: ( startSpanOptions: StartSpanOptions, options?: Partial<IdleSpanOptions>) => Span;
An idle span is a span that automatically finishes. It does this by tracking child spans as activities. An idle span is always the active span.
function startInactiveSpan
startInactiveSpan: (options: StartSpanOptions) => Span;
Creates a span. This span is not set as active, so will not get automatic instrumentation spans as children or be able to be accessed via
Sentry.getActiveSpan()
.If you want to create a span that is set as active, use startSpan.
This function will always return a span, it may just be a non-recording span if the span is not sampled or if tracing is disabled.
function startNewTrace
startNewTrace: <T>(callback: () => T) => T;
Starts a new trace for the duration of the provided callback. Spans started within the callback will be part of the new trace instead of a potentially previously started trace.
Important: Only use this function if you want to override the default trace lifetime and propagation mechanism of the SDK for the duration and scope of the provided callback. The newly created trace will also be the root of a new distributed trace, for example if you make http requests within the callback. This function might be useful if the operation you want to instrument should not be part of a potentially ongoing trace.
Default behavior: - Server-side: A new trace is started for each incoming request. - Browser: A new trace is started for each page our route. Navigating to a new route or page will automatically create a new trace.
function startSession
startSession: (context?: SessionContext) => Session;
Start a session on the current isolation scope.
Parameter context
(optional) additional properties to be applied to the returned session object
Returns
the new active session
function startSpan
startSpan: <T>(options: StartSpanOptions, callback: (span: Span) => T) => T;
Wraps a function with a transaction/span and finishes the span after the function is done. The created span is the active span and will be used as parent by other spans created inside the function and can be accessed via
Sentry.getActiveSpan()
, as long as the function is executed while the scope is active.If you want to create a span that is not set as active, use startInactiveSpan.
You'll always get a span passed to the callback, it may just be a non-recording span if the span is not sampled or if tracing is disabled.
function startSpanManual
startSpanManual: <T>( options: StartSpanOptions, callback: (span: Span, finish: () => void) => T) => T;
Similar to
Sentry.startSpan
. Wraps a function with a transaction/span, but does not finish the span after the function is done automatically. You'll have to callspan.end()
manually.The created span is the active span and will be used as parent by other spans created inside the function and can be accessed via
Sentry.getActiveSpan()
, as long as the function is executed while the scope is active.You'll always get a span passed to the callback, it may just be a non-recording span if the span is not sampled or if tracing is disabled.
function stringMatchesSomePattern
stringMatchesSomePattern: ( testString: string, patterns?: Array<string | RegExp>, requireExactStringMatch?: boolean) => boolean;
Test the given string against an array of strings and regexes. By default, string matching is done on a substring-inclusion basis rather than a strict equality basis
Parameter testString
The string to test
Parameter patterns
The patterns against which to test the string
Parameter requireExactStringMatch
If true,
testString
must match one of the given string patterns exactly in order to count. If false,testString
will match a string pattern if it contains that pattern.Returns
function stripSentryFramesAndReverse
stripSentryFramesAndReverse: (stack: ReadonlyArray<StackFrame>) => StackFrame[];
Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames. Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the function that caused the crash is the last frame in the array.
function stripUrlQueryAndFragment
stripUrlQueryAndFragment: (urlPath: string) => string;
Strip the query string and fragment off of a given URL or path (if present)
Parameter urlPath
Full URL or path, including possible query string and/or fragment
Returns
URL or path without query string or fragment
function supportsDOMError
supportsDOMError: () => boolean;
Tells whether current environment supports DOMError objects supportsDOMError.
Returns
Answer to the given question.
function supportsDOMException
supportsDOMException: () => boolean;
Tells whether current environment supports DOMException objects supportsDOMException.
Returns
Answer to the given question.
function supportsErrorEvent
supportsErrorEvent: () => boolean;
Tells whether current environment supports ErrorEvent objects supportsErrorEvent.
Returns
Answer to the given question.
function supportsFetch
supportsFetch: () => boolean;
Tells whether current environment supports Fetch API supportsFetch.
Returns
Answer to the given question.
function supportsHistory
supportsHistory: () => boolean;
Tells whether current environment supports History API supportsHistory.
Returns
Answer to the given question.
function supportsNativeFetch
supportsNativeFetch: () => boolean;
Tells whether current environment supports Fetch API natively supportsNativeFetch.
Returns
true if
window.fetch
is natively implemented, false otherwise
function supportsReferrerPolicy
supportsReferrerPolicy: () => boolean;
Tells whether current environment supports Referrer Policy API supportsReferrerPolicy.
Returns
Answer to the given question.
function supportsReportingObserver
supportsReportingObserver: () => boolean;
Tells whether current environment supports ReportingObserver API supportsReportingObserver.
Returns
Answer to the given question.
function suppressTracing
suppressTracing: <T>(callback: () => T) => T;
Suppress tracing in the given callback, ensuring no spans are generated inside of it.
function thirdPartyErrorFilterIntegration
thirdPartyErrorFilterIntegration: ( options: Options) => import('../types-hoist').Integration;
This integration allows you to filter out, or tag error events that do not come from user code marked with a bundle key via the Sentry bundler plugins.
function timedEventsToMeasurements
timedEventsToMeasurements: (events: TimedEvent[]) => Measurements | undefined;
Convert timed events to measurements.
function timestampInSeconds
timestampInSeconds: () => number;
Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the availability of the Performance API.
BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is asleep. This creates a skew between
dateTimestampInSeconds
andtimestampInSeconds
. The skew can grow to arbitrary amounts like days, weeks or months. See https://github.com/getsentry/sentry-javascript/issues/2590.
function triggerHandlers
triggerHandlers: (type: InstrumentHandlerType, data: unknown) => void;
Trigger handlers for a given instrumentation type.
function trpcMiddleware
trpcMiddleware: ( options?: SentryTrpcMiddlewareOptions) => <T>(opts: SentryTrpcMiddlewareArguments<T>) => SentryTrpcMiddleware<T>;
Sentry tRPC middleware that captures errors and creates spans for tRPC procedures.
function truncate
truncate: (str: string, max?: number) => string;
Truncates given string to the maximum characters count
Parameter str
An object that contains serializable values
Parameter max
Maximum number of characters in truncated string (0 = unlimited)
Returns
string Encoded
function updateRateLimits
updateRateLimits: ( limits: RateLimits, { statusCode, headers }: TransportMakeRequestResponse, now?: number) => RateLimits;
Update ratelimits from incoming headers.
the updated RateLimits object.
function updateSession
updateSession: (session: Session, context?: SessionContext) => void;
Updates a session object with the properties passed in the context.
Note that this function mutates the passed object and returns void. (Had to do this instead of returning a new and updated session because closing and sending a session makes an update to the session after it was passed to the sending logic.
Parameter session
the
Session
to updateParameter context
the
SessionContext
holding the properties that should be updated inParameter session
See Also
BaseClient.captureSession )
function urlEncode
urlEncode: (object: { [key: string]: any }) => string;
Encodes given object into url-friendly format
Parameter object
An object that contains serializable values
Returns
string Encoded
Deprecated
This function is deprecated and will be removed in the next major version of the SDK.
function uuid4
uuid4: () => string;
UUID4 generator
Returns
string Generated UUID4.
function vercelWaitUntil
vercelWaitUntil: (task: Promise<unknown>) => void;
Function that delays closing of a Vercel lambda until the provided promise is resolved.
Vendored from https://www.npmjs.com/package/@vercel/functions
function watchdogTimer
watchdogTimer: ( createTimer: CreateTimerImpl, pollInterval: number, anrThreshold: number, callback: () => void) => WatchdogReturn;
A node.js watchdog timer
Parameter pollInterval
The interval that we expect to get polled at
Parameter anrThreshold
The threshold for when we consider ANR
Parameter callback
The callback to call for ANR
Returns
An object with
poll
andenabled
functions WatchdogReturn
function winterCGHeadersToDict
winterCGHeadersToDict: ( winterCGHeaders: WebFetchHeaders) => Record<string, string>;
Transforms a
Headers
object that implements theWeb Fetch API
(https://developer.mozilla.org/en-US/docs/Web/API/Headers) into a simple key-value dict. The header keys will be lower case: e.g. A "Content-Type" header will be stored as "content-type".
function winterCGRequestToRequestData
winterCGRequestToRequestData: (req: WebFetchRequest) => RequestEventData;
Converts a
Request
object that implements theWeb Fetch API
(https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that theRequestData
integration understands.
function withActiveSpan
withActiveSpan: <T>(span: Span | null, callback: (scope: Scope) => T) => T;
Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be passed
null
to start an entirely new span tree.Parameter span
Spans started in the context of the provided callback will be children of this span. If
null
is passed, spans started within the callback will not be attached to a parent span.Parameter callback
Execution context in which the provided span will be active. Is passed the newly forked scope.
Returns
the value returned from the provided callback function.
function withIsolationScope
withIsolationScope: { <T>(callback: (isolationScope: Scope) => T): T; <T>(isolationScope: Scope, callback: (isolationScope: Scope) => T): T;};
Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the case, for example, in the browser).
Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.
This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in "normal" applications directly because it comes with pitfalls. Use at your own risk!
Set the provided isolation scope as active in the given callback. If no async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the case, for example, in the browser).
Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.
This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in "normal" applications directly because it comes with pitfalls. Use at your own risk!
If you pass in
undefined
as a scope, it will fork a new isolation scope, the same as if no scope is passed.
function withMonitor
withMonitor: <T>( monitorSlug: CheckIn['monitorSlug'], callback: () => T, upsertMonitorConfig?: MonitorConfig) => T;
Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.
Parameter monitorSlug
The distinct slug of the monitor.
Parameter upsertMonitorConfig
An optional object that describes a monitor config. Use this if you want to create a monitor automatically when sending a check in.
function withScope
withScope: { <T>(callback: (scope: Scope) => T): T; <T>(scope: Scope, callback: (scope: Scope) => T): T;};
Creates a new scope with and executes the given operation within. The scope is automatically removed once the operation finishes or throws.
Set the given scope as the active scope in the callback.
function zodErrorsIntegration
zodErrorsIntegration: ( options?: ZodErrorsOptions | undefined) => import('../types-hoist').Integration;
Classes
class BaseClient
abstract class BaseClient<O extends ClientOptions> implements Client<O> {}
Base implementation for all JavaScript SDK clients.
Call the constructor with the corresponding options specific to the client subclass. To access these options later, use Client.getOptions.
If a Dsn is specified in the options, it will be parsed and stored. Use Client.getDsn to retrieve the Dsn at any moment. In case the Dsn is invalid, the constructor will throw a SentryException. Note that without a valid Dsn, the SDK will not send any events to Sentry.
Before sending an event, it is passed through BaseClient._prepareEvent to add SDK information and scope data (breadcrumbs and context). To add more custom information, override this method and extend the resulting prepared event.
To issue automatically created events (e.g. via instrumentation), use Client.captureEvent. It will prepare the event and pass it through the callback lifecycle. To issue auto-breadcrumbs, use Client.addBreadcrumb.
Example 1
class NodeClient extends BaseClient { public constructor(options: NodeOptions) { super(options); }
// ... }
constructor
protected constructor(options: ClientOptions<BaseTransportOptions>);
Initializes this client instance.
Parameter options
Options for the client.
method addEventProcessor
addEventProcessor: (eventProcessor: EventProcessor) => void;
method addIntegration
addIntegration: (integration: Integration) => void;
method captureEvent
captureEvent: (event: Event, hint?: EventHint, currentScope?: Scope) => string;
method captureException
captureException: (exception: any, hint?: EventHint, scope?: Scope) => string;
method captureMessage
captureMessage: ( message: ParameterizedString, level?: SeverityLevel, hint?: EventHint, currentScope?: Scope) => string;
method captureSession
captureSession: (session: Session) => void;
method close
close: (timeout?: number) => PromiseLike<boolean>;
method emit
emit: { ( hook: 'beforeSampling', samplingData: { spanAttributes: SpanAttributes; spanName: string; parentSampled?: boolean; parentContext?: SpanContextData; }, samplingDecision: { decision: boolean } ): void; (hook: 'spanStart', span: Span): void; (hook: 'spanEnd', span: Span): void; (hook: 'idleSpanEnableAutoFinish', span: Span): void; (hook: 'beforeEnvelope', envelope: Envelope): void; (hook: 'beforeSendEvent', event: Event, hint?: EventHint): void; (hook: 'preprocessEvent', event: Event, hint?: EventHint): void; ( hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse ): void; ( hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint ): void; (hook: 'createDsc', dsc: DynamicSamplingContext, rootSpan?: Span): void; ( hook: 'beforeSendFeedback', feedback: FeedbackEvent, options?: { includeReplay: boolean } ): void; ( hook: 'startPageLoadSpan', options: StartSpanOptions, traceOptions?: { sentryTrace?: string; baggage?: string } ): void; (hook: 'startNavigationSpan', options: StartSpanOptions): void; (hook: 'flush'): void; (hook: 'close'): void; (hook: 'applyFrameMetadata', event: Event): void;};
method eventFromException
abstract eventFromException: ( _exception: any, _hint?: EventHint) => PromiseLike<Event>;
method eventFromMessage
abstract eventFromMessage: ( _message: ParameterizedString, _level?: SeverityLevel, _hint?: EventHint) => PromiseLike<Event>;
method flush
flush: (timeout?: number) => PromiseLike<boolean>;
method getDsn
getDsn: () => DsnComponents | undefined;
method getEventProcessors
getEventProcessors: () => EventProcessor[];
Get all installed event processors.
method getIntegrationByName
getIntegrationByName: <T extends Integration = Integration>( integrationName: string) => T | undefined;
Gets an installed integration by its name.
Returns
The installed integration or
undefined
if no integration with thatname
was installed.
method getOptions
getOptions: () => O;
method getSdkMetadata
getSdkMetadata: () => SdkMetadata | undefined;
See Also
SdkMetadata
The metadata of the SDK
method getTransport
getTransport: () => Transport | undefined;
method init
init: () => void;
method on
on: { (hook: 'spanStart', callback: (span: Span) => void): () => void; (hook: 'spanEnd', callback: (span: Span) => void): () => void; ( hook: 'idleSpanEnableAutoFinish', callback: (span: Span) => void ): () => void; (hook: 'beforeEnvelope', callback: (envelope: Envelope) => void): () => void; ( hook: 'beforeSendEvent', callback: (event: Event, hint?: EventHint) => void ): () => void; ( hook: 'preprocessEvent', callback: (event: Event, hint?: EventHint) => void ): () => void; ( hook: 'afterSendEvent', callback: ( event: Event, sendResponse: TransportMakeRequestResponse ) => void ): () => void; ( hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void ): () => void; ( hook: 'createDsc', callback: (dsc: DynamicSamplingContext, rootSpan?: Span) => void ): () => void; ( hook: 'beforeSendFeedback', callback: ( feedback: FeedbackEvent, options?: { includeReplay: boolean } ) => void ): () => void; ( hook: 'beforeSampling', callback: ( samplingData: { spanAttributes: SpanAttributes; spanName: string; parentSampled?: boolean; parentContext?: SpanContextData; }, samplingDecision: { decision: boolean } ) => void ): void; ( hook: 'startPageLoadSpan', callback: ( options: StartSpanOptions, traceOptions?: { sentryTrace?: string; baggage?: string } ) => void ): () => void; ( hook: 'startNavigationSpan', callback: (options: StartSpanOptions) => void ): () => void; (hook: 'flush', callback: () => void): () => void; (hook: 'close', callback: () => void): () => void; (hook: 'applyFrameMetadata', callback: (event: Event) => void): () => void;};
method recordDroppedEvent
recordDroppedEvent: ( reason: EventDropReason, category: DataCategory, eventOrCount?: Event | number) => void;
method sendEnvelope
sendEnvelope: (envelope: Envelope) => PromiseLike<TransportMakeRequestResponse>;
method sendEvent
sendEvent: (event: Event, hint?: EventHint) => void;
method sendSession
sendSession: (session: Session | SessionAggregates) => void;
class BrowserMetricsAggregator
class BrowserMetricsAggregator implements MetricsAggregator {}
A simple metrics aggregator that aggregates metrics in memory and flushes them periodically. Default flush interval is 5 seconds.
This API is experimental and might change in the future.
Modifiers
@experimental
constructor
constructor(_client: Client<ClientOptions<BaseTransportOptions>>);
method add
add: ( metricType: MetricType, unsanitizedName: string, value: number | string, unsanitizedUnit?: MeasurementUnit | undefined, unsanitizedTags?: Record<string, Primitive> | undefined, maybeFloatTimestamp?: number | undefined) => void;
method close
close: () => void;
method flush
flush: () => void;
class LRUMap
class LRUMap<K, V> {}
A simple Least Recently Used map
constructor
constructor(_maxSize: number);
property size
readonly size: number;
Get the current size of the cache
method clear
clear: () => void;
Clear all entries
method get
get: (key: K) => V | undefined;
Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order
method keys
keys: () => Array<K>;
Get all the keys
method remove
remove: (key: K) => V | undefined;
Remove an entry and return the entry if it was in the cache
method set
set: (key: K, value: V) => void;
Insert an entry and evict an older entry if we've reached maxSize
method values
values: () => Array<V>;
Get all the values
class SentryError
class SentryError extends Error {}
An error emitted by Sentry SDKs and related utilities.
constructor
constructor(message: string, logLevel?: ConsoleLevel);
property logLevel
logLevel: ConsoleLevel;
property message
message: string;
property name
name: string;
Display name of this error instance.
class SentryNonRecordingSpan
class SentryNonRecordingSpan implements Span {}
A Sentry Span that is non-recording, meaning it will not be sent to Sentry.
constructor
constructor(spanContext?: SentrySpanArguments);
method addEvent
addEvent: ( _name: string, _attributesOrStartTime?: SpanAttributes | SpanTimeInput, _startTime?: SpanTimeInput) => this;
method end
end: (_timestamp?: SpanTimeInput) => void;
method isRecording
isRecording: () => boolean;
method setAttribute
setAttribute: (_key: string, _value: SpanAttributeValue | undefined) => this;
method setAttributes
setAttributes: (_values: SpanAttributes) => this;
method setStatus
setStatus: (_status: SpanStatus) => this;
method spanContext
spanContext: () => SpanContextData;
method updateName
updateName: (_name: string) => this;
class SentrySpan
class SentrySpan implements Span {}
Span contains all data about a span