0
# Core Sentry Functionality
1
2
All core Sentry capabilities for error tracking, performance monitoring, context management, and SDK configuration. The @sentry/serverless package re-exports all functionality from @sentry/node, providing the complete Sentry experience for serverless environments.
3
4
## Capabilities
5
6
### Initialization
7
8
Initialize the Sentry SDK with configuration options.
9
10
```typescript { .api }
11
/**
12
* Initialize the Sentry SDK
13
* @param options - Configuration options for the SDK
14
*/
15
function init(options?: NodeOptions): void;
16
17
interface NodeOptions {
18
/** Data Source Name - your Sentry project URL */
19
dsn?: string;
20
/** Application environment (e.g., 'production', 'development') */
21
environment?: string;
22
/** Application release version */
23
release?: string;
24
/** Sample rate for error events (0.0 to 1.0) */
25
sampleRate?: number;
26
/** Sample rate for performance/tracing events (0.0 to 1.0) */
27
tracesSampleRate?: number;
28
/** Whether to attach stack traces to messages */
29
attachStacktrace?: boolean;
30
/** Array of integrations to use */
31
integrations?: Integration[];
32
/** Whether to send sessions */
33
autoSessionTracking?: boolean;
34
/** Custom transport function */
35
transport?: Transport;
36
/** Custom stack parser */
37
stackParser?: StackParser;
38
}
39
40
// Base Sentry types
41
interface Integration {
42
name: string;
43
setupOnce?(): void;
44
setup?(client: Client): void;
45
}
46
47
interface Client {
48
captureException(exception: any, hint?: EventHint, scope?: Scope): string;
49
captureMessage(message: string, level?: SeverityLevel, hint?: EventHint, scope?: Scope): string;
50
captureEvent(event: Event, hint?: EventHint, scope?: Scope): string;
51
flush(timeout?: number): Promise<boolean>;
52
close(timeout?: number): Promise<boolean>;
53
}
54
55
interface Options {
56
dsn?: string;
57
environment?: string;
58
release?: string;
59
integrations?: Integration[];
60
[key: string]: any;
61
}
62
```
63
64
### Error Capture
65
66
Capture and send exceptions and messages to Sentry.
67
68
```typescript { .api }
69
/**
70
* Capture and send an exception to Sentry
71
* @param exception - The exception to capture
72
* @param scope - Optional scope modifier function
73
* @returns Event ID of the captured exception
74
*/
75
function captureException(
76
exception: any,
77
scope?: (scope: Scope) => Scope
78
): string;
79
80
/**
81
* Capture and send a message to Sentry
82
* @param message - The message to capture
83
* @param level - Severity level of the message
84
* @param scope - Optional scope modifier function
85
* @returns Event ID of the captured message
86
*/
87
function captureMessage(
88
message: string,
89
level?: SeverityLevel,
90
scope?: (scope: Scope) => Scope
91
): string;
92
93
/**
94
* Capture and send an event to Sentry
95
* @param event - The event object to send
96
* @param scope - Optional scope modifier function
97
* @returns Event ID of the captured event
98
*/
99
function captureEvent(
100
event: Event,
101
scope?: (scope: Scope) => Scope
102
): string;
103
104
type SeverityLevel = 'fatal' | 'error' | 'warning' | 'log' | 'info' | 'debug';
105
```
106
107
**Usage Examples:**
108
109
```typescript
110
import { captureException, captureMessage, captureEvent } from "@sentry/serverless";
111
112
// Capture an exception
113
try {
114
riskyOperation();
115
} catch (error) {
116
captureException(error);
117
}
118
119
// Capture a message with context
120
captureMessage("User login failed", "warning", (scope) => {
121
scope.setTag("feature", "authentication");
122
scope.setUser({ id: "123", email: "user@example.com" });
123
return scope;
124
});
125
126
// Capture a custom event
127
captureEvent({
128
message: "Custom business logic event",
129
level: "info",
130
tags: {
131
module: "payment-processor",
132
action: "payment-completed"
133
}
134
});
135
```
136
137
### Performance Monitoring
138
139
Create and manage performance spans and transactions.
140
141
```typescript { .api }
142
/**
143
* Start a new span and execute a function within its context
144
* @param context - Span context configuration
145
* @param fn - Function to execute within the span
146
* @returns Result of the function execution
147
*/
148
function startSpan<T>(context: SpanContext, fn: (span: Span) => T): T;
149
150
/**
151
* Start a span with manual control over its lifecycle
152
* @param context - Span context configuration
153
* @param fn - Function to execute with manual span control
154
* @returns Result of the function execution
155
*/
156
function startSpanManual<T>(context: SpanContext, fn: (span: Span) => T): T;
157
158
/**
159
* Start an inactive span that doesn't affect the active span context
160
* @param context - Span context configuration
161
* @returns The created span
162
*/
163
function startInactiveSpan(context: SpanContext): Span;
164
165
/**
166
* Execute code with a specific span as the active span
167
* @param span - The span to make active
168
* @param fn - Function to execute with the active span
169
* @returns Result of the function execution
170
*/
171
function withActiveSpan<T>(span: Span | null, fn: () => T): T;
172
173
/**
174
* Get the currently active span
175
* @returns The active span or undefined
176
*/
177
function getActiveSpan(): Span | undefined;
178
179
interface SpanContext {
180
/** Name of the span */
181
name: string;
182
/** Operation type (e.g., 'http.client', 'db.query') */
183
op?: string;
184
/** Span attributes */
185
attributes?: Record<string, any>;
186
/** Parent span ID */
187
parentSpanId?: string;
188
/** Trace ID */
189
traceId?: string;
190
/** Whether this span should only be created if there's a parent */
191
onlyIfParent?: boolean;
192
}
193
```
194
195
**Usage Examples:**
196
197
```typescript
198
import { startSpan, startSpanManual, getActiveSpan } from "@sentry/serverless";
199
200
// Automatic span management
201
const result = await startSpan(
202
{ name: "database-query", op: "db.query" },
203
async (span) => {
204
span.setTag("table", "users");
205
span.setData("query", "SELECT * FROM users WHERE active = true");
206
207
return await db.query("SELECT * FROM users WHERE active = true");
208
}
209
);
210
211
// Manual span management
212
const data = await startSpanManual(
213
{ name: "complex-operation", op: "task" },
214
async (span) => {
215
try {
216
const step1 = await performStep1();
217
span.setTag("step1_status", "success");
218
219
const step2 = await performStep2(step1);
220
span.setTag("step2_status", "success");
221
222
return step2;
223
} catch (error) {
224
span.setTag("error", true);
225
span.setStatus("internal_error");
226
throw error;
227
} finally {
228
span.end();
229
}
230
}
231
);
232
233
// Check for active span
234
const activeSpan = getActiveSpan();
235
if (activeSpan) {
236
activeSpan.setTag("has_active_span", true);
237
}
238
```
239
240
### Context Management
241
242
Manage Sentry scopes and context data.
243
244
```typescript { .api }
245
/**
246
* Execute code within an isolated scope
247
* @param callback - Function to execute with the isolated scope
248
* @returns Result of the callback function
249
*/
250
function withScope<T>(callback: (scope: Scope) => T): T;
251
252
/**
253
* Execute code within an isolated isolation scope
254
* @param callback - Function to execute with the isolation scope
255
* @returns Result of the callback function
256
*/
257
function withIsolationScope<T>(callback: (scope: Scope) => T): T;
258
259
/**
260
* Get the current scope
261
* @returns The current scope
262
*/
263
function getCurrentScope(): Scope;
264
265
/**
266
* Get the global scope
267
* @returns The global scope
268
*/
269
function getGlobalScope(): Scope;
270
271
/**
272
* Get the isolation scope
273
* @returns The isolation scope
274
*/
275
function getIsolationScope(): Scope;
276
277
// Convenience functions for setting context
278
function setContext(key: string, context: Context): void;
279
function setExtra(key: string, extra: any): void;
280
function setExtras(extras: Record<string, any>): void;
281
function setTag(key: string, value: string): void;
282
function setTags(tags: Record<string, string>): void;
283
function setUser(user: User): void;
284
285
interface Scope {
286
/** Set a tag on the scope */
287
setTag(key: string, value: string): void;
288
/** Set multiple tags on the scope */
289
setTags(tags: Record<string, string>): void;
290
/** Set extra data on the scope */
291
setExtra(key: string, extra: any): void;
292
/** Set multiple extra data on the scope */
293
setExtras(extras: Record<string, any>): void;
294
/** Set context on the scope */
295
setContext(key: string, context: Context): void;
296
/** Set user information on the scope */
297
setUser(user: User | null): void;
298
/** Add a breadcrumb to the scope */
299
addBreadcrumb(breadcrumb: Breadcrumb): void;
300
/** Add an event processor to the scope */
301
addEventProcessor(callback: EventProcessor): void;
302
}
303
304
interface User {
305
id?: string | number;
306
username?: string;
307
email?: string;
308
ip_address?: string;
309
[key: string]: any;
310
}
311
312
interface Context {
313
[key: string]: any;
314
}
315
```
316
317
**Usage Examples:**
318
319
```typescript
320
import {
321
withScope,
322
getCurrentScope,
323
setUser,
324
setTag,
325
setContext,
326
captureException
327
} from "@sentry/serverless";
328
329
// Isolated scope for specific operation
330
withScope((scope) => {
331
scope.setTag("operation", "user-registration");
332
scope.setUser({ id: "123", email: "user@example.com" });
333
scope.setContext("registration", { step: "email-verification" });
334
335
try {
336
registerUser(userData);
337
} catch (error) {
338
captureException(error); // Will include the scope context
339
}
340
});
341
342
// Global context setting
343
setUser({ id: "456", email: "admin@example.com" });
344
setTag("service", "user-service");
345
setContext("deployment", { version: "1.2.3", region: "us-west-2" });
346
347
// Working with current scope
348
const scope = getCurrentScope();
349
scope.addBreadcrumb({
350
message: "Started processing request",
351
category: "request",
352
level: "info",
353
timestamp: Date.now() / 1000
354
});
355
```
356
357
### Breadcrumbs
358
359
Add breadcrumb trails to track user actions and application state.
360
361
```typescript { .api }
362
/**
363
* Add a breadcrumb to the current scope
364
* @param breadcrumb - The breadcrumb to add
365
*/
366
function addBreadcrumb(breadcrumb: Breadcrumb): void;
367
368
interface Breadcrumb {
369
/** Breadcrumb message */
370
message?: string;
371
/** Breadcrumb category */
372
category?: string;
373
/** Breadcrumb level */
374
level?: BreadcrumbLevel;
375
/** Breadcrumb timestamp */
376
timestamp?: number;
377
/** Breadcrumb type */
378
type?: string;
379
/** Additional data */
380
data?: Record<string, any>;
381
}
382
383
type BreadcrumbLevel = 'fatal' | 'error' | 'warning' | 'info' | 'debug';
384
```
385
386
### SDK Management
387
388
Manage SDK state and configuration.
389
390
```typescript { .api }
391
/**
392
* Check if the SDK is initialized
393
* @returns True if the SDK is initialized
394
*/
395
function isInitialized(): boolean;
396
397
/**
398
* Get the current Sentry client
399
* @returns The current client or undefined
400
*/
401
function getClient(): Client | undefined;
402
403
/**
404
* Set the current client
405
* @param client - The client to set as current
406
*/
407
function setCurrentClient(client: Client): void;
408
409
/**
410
* Flush pending events
411
* @param timeout - Maximum time to wait for flush in milliseconds
412
* @returns Promise that resolves when flush is complete
413
*/
414
function flush(timeout?: number): Promise<boolean>;
415
416
/**
417
* Close the SDK and flush all pending events
418
* @param timeout - Maximum time to wait for close in milliseconds
419
* @returns Promise that resolves when close is complete
420
*/
421
function close(timeout?: number): Promise<boolean>;
422
423
/**
424
* Get the last captured event ID
425
* @returns The event ID of the last captured event
426
*/
427
function lastEventId(): string | undefined;
428
```
429
430
### Integrations
431
432
Manage SDK integrations for enhanced functionality.
433
434
```typescript { .api }
435
/**
436
* Add an integration after SDK initialization
437
* @param integration - The integration to add
438
*/
439
function addIntegration(integration: Integration): void;
440
441
/**
442
* Get the default integrations for Node.js
443
* @param options - Configuration options
444
* @returns Array of default integrations
445
*/
446
function getDefaultIntegrations(options: Options): Integration[];
447
448
/**
449
* Auto-discover Node.js performance monitoring integrations
450
* @returns Array of performance integrations
451
*/
452
function autoDiscoverNodePerformanceMonitoringIntegrations(): Integration[];
453
454
// Built-in integrations
455
function consoleIntegration(options?: ConsoleOptions): Integration;
456
function httpIntegration(options?: HttpOptions): Integration;
457
function onUncaughtExceptionIntegration(options?: UncaughtExceptionOptions): Integration;
458
function onUnhandledRejectionIntegration(options?: UnhandledRejectionOptions): Integration;
459
function localVariablesIntegration(options?: LocalVariablesOptions): Integration;
460
function contextLinesIntegration(options?: ContextLinesOptions): Integration;
461
function anrIntegration(options?: ANROptions): Integration;
462
```
463
464
### Transport and Serialization
465
466
Control how events are sent to Sentry.
467
468
```typescript { .api }
469
/**
470
* Create a custom transport
471
* @param options - Transport configuration
472
* @returns Transport instance
473
*/
474
function createTransport(options: TransportOptions): Transport;
475
476
/**
477
* Create the default Node.js transport
478
* @param options - Transport configuration
479
* @returns Transport instance
480
*/
481
function makeNodeTransport(options: TransportOptions): Transport;
482
483
/**
484
* Continue a trace from headers
485
* @param headers - Headers containing trace information
486
* @param callback - Function to execute within the continued trace
487
* @returns Result of the callback
488
*/
489
function continueTrace<T>(
490
headers: { sentryTrace?: string; baggage?: string },
491
callback: () => T
492
): T;
493
```
494
495
## Session Management
496
497
Track user sessions for release health monitoring.
498
499
```typescript { .api }
500
/**
501
* Start a new session
502
* @param context - Session context
503
*/
504
function startSession(context?: SessionContext): void;
505
506
/**
507
* Capture the current session
508
*/
509
function captureSession(): void;
510
511
/**
512
* End the current session
513
*/
514
function endSession(): void;
515
516
interface SessionContext {
517
user?: User;
518
release?: string;
519
environment?: string;
520
}
521
```
522
523
This comprehensive core functionality provides all the essential Sentry capabilities needed for error monitoring, performance tracking, and application observability in serverless environments.