0
# AWS Lambda Integration
1
2
Complete AWS Lambda support with handler wrapping, automatic context enhancement, AWS services integration, and performance tracing capabilities specifically designed for the Lambda execution environment.
3
4
## Capabilities
5
6
### Initialization
7
8
Initialize the Sentry AWS Lambda SDK with platform-specific configurations and integrations.
9
10
```typescript { .api }
11
/**
12
* Initializes the Sentry AWS Lambda SDK
13
* @param options - Configuration options for the SDK
14
*/
15
function init(options?: AWSLambdaOptions): void;
16
17
interface AWSLambdaOptions extends NodeOptions {
18
/** Internal field that is set to true when init() is called by the Sentry AWS Lambda layer */
19
_invokedByLambdaLayer?: boolean;
20
}
21
```
22
23
**Usage Examples:**
24
25
```typescript
26
import { AWSLambda } from "@sentry/serverless";
27
28
// Basic initialization
29
AWSLambda.init({
30
dsn: "your-dsn-here",
31
});
32
33
// With performance tracing
34
AWSLambda.init({
35
dsn: "your-dsn-here",
36
tracesSampleRate: 1.0,
37
environment: "production",
38
});
39
40
// With custom integrations
41
AWSLambda.init({
42
dsn: "your-dsn-here",
43
integrations: [
44
// Add custom integrations
45
],
46
});
47
```
48
49
### Handler Wrapping
50
51
Wraps Lambda handlers to add error capture, performance tracing, and automatic context enhancement.
52
53
```typescript { .api }
54
/**
55
* Wraps a lambda handler adding it error capture and tracing capabilities
56
* @param handler - AWS Lambda handler function
57
* @param wrapOptions - Optional configuration for wrapper behavior
58
* @returns Wrapped handler with Sentry capabilities
59
*/
60
function wrapHandler<TEvent, TResult>(
61
handler: Handler<TEvent, TResult>,
62
wrapOptions?: Partial<AWSLambdaWrapperOptions>
63
): Handler<TEvent, TResult>;
64
65
// Handler type from AWS Lambda types
66
type Handler<TEvent = any, TResult = any> = (
67
event: TEvent,
68
context: Context,
69
callback?: Callback<TResult>
70
) => void | Promise<TResult>;
71
72
interface AWSLambdaWrapperOptions {
73
/** Timeout for flushing events before Lambda terminates (default: 2000ms) */
74
flushTimeout: number;
75
/** Whether callback waits for empty event loop (default: false) */
76
callbackWaitsForEmptyEventLoop: boolean;
77
/** Whether to capture timeout warnings (default: true) */
78
captureTimeoutWarning: boolean;
79
/** Timeout warning threshold in milliseconds (default: 500) */
80
timeoutWarningLimit: number;
81
/** Capture all errors when Promise.allSettled is returned (default: false) */
82
captureAllSettledReasons: boolean;
83
/** Automatically trace all handler invocations (default: true) */
84
startTrace: boolean;
85
}
86
87
type AsyncHandler<T extends Handler> = (
88
event: Parameters<T>[0],
89
context: Parameters<T>[1]
90
) => Promise<NonNullable<Parameters<Parameters<T>[2]>[1]>>;
91
```
92
93
**Usage Examples:**
94
95
```typescript
96
import { AWSLambda } from "@sentry/serverless";
97
98
// Basic async handler wrapping
99
exports.handler = AWSLambda.wrapHandler(async (event, context) => {
100
// Your handler logic
101
return { statusCode: 200, body: "Success" };
102
});
103
104
// Sync handler with callback
105
exports.handler = AWSLambda.wrapHandler((event, context, callback) => {
106
// Your handler logic
107
callback(null, { statusCode: 200, body: "Success" });
108
});
109
110
// With custom wrapper options
111
exports.handler = AWSLambda.wrapHandler(async (event, context) => {
112
// Handler logic
113
return await processEvent(event);
114
}, {
115
flushTimeout: 5000,
116
captureTimeoutWarning: true,
117
timeoutWarningLimit: 1000,
118
captureAllSettledReasons: true
119
});
120
121
// Handle Promise.allSettled patterns
122
exports.handler = AWSLambda.wrapHandler(async (event, context) => {
123
// This will automatically capture errors from rejected promises
124
return await Promise.allSettled([
125
processItem(event.item1),
126
processItem(event.item2),
127
processItem(event.item3)
128
]);
129
}, {
130
captureAllSettledReasons: true
131
});
132
```
133
134
### Auto-Patching
135
136
Automatically patch existing Lambda handlers without manual wrapping.
137
138
```typescript { .api }
139
/**
140
* Attempts to automatically patch the Lambda handler
141
* @param taskRoot - Root directory path where handler is located
142
* @param handlerPath - Path to the handler function (e.g., "index.handler")
143
*/
144
function tryPatchHandler(taskRoot: string, handlerPath: string): void;
145
```
146
147
**Usage Examples:**
148
149
```typescript
150
import { AWSLambda } from "@sentry/serverless";
151
152
// Automatically patch handler based on environment
153
AWSLambda.tryPatchHandler(process.env.LAMBDA_TASK_ROOT || "/var/task", "index.handler");
154
```
155
156
### Default Integrations
157
158
Get the default integrations configured for AWS Lambda environment.
159
160
```typescript { .api }
161
/**
162
* Get the default integrations for the AWSLambda SDK
163
* @param options - SDK options to configure integrations
164
* @returns Array of default integrations including AWS services integration
165
*/
166
function getDefaultIntegrations(options: Options): Integration[];
167
168
/** @deprecated Use getDefaultIntegrations(options) instead */
169
const defaultIntegrations: Integration[];
170
```
171
172
**Usage Examples:**
173
174
```typescript
175
import { AWSLambda } from "@sentry/serverless";
176
177
// Get default integrations
178
const integrations = AWSLambda.getDefaultIntegrations({
179
// configuration options
180
});
181
182
// Use in custom initialization
183
AWSLambda.init({
184
dsn: "your-dsn-here",
185
integrations: [
186
...AWSLambda.getDefaultIntegrations({}),
187
// Add additional custom integrations
188
]
189
});
190
```
191
192
## Context Enhancement
193
194
The AWS Lambda integration automatically enhances Sentry scopes with Lambda-specific context:
195
196
### AWS Lambda Context
197
198
```typescript
199
// Automatically added to scope
200
{
201
"aws.lambda": {
202
"aws_request_id": "8476a536-e9f4-11e8-9739-2dfe598c3fcd",
203
"function_name": "myLambdaFunction",
204
"function_version": "$LATEST",
205
"invoked_function_arn": "arn:aws:lambda:us-west-2:123456789012:function:myLambdaFunction",
206
"execution_duration_in_millis": 108.20,
207
"remaining_time_in_millis": 691789,
208
"sys.argv": ["/var/runtime/bootstrap"]
209
}
210
}
211
```
212
213
### CloudWatch Logs Context
214
215
```typescript
216
// Automatically added to scope
217
{
218
"aws.cloudwatch.logs": {
219
"log_group": "/aws/lambda/myLambdaFunction",
220
"log_stream": "2018/11/13/[$LATEST]8bcc747eb4ff4897bf6eba48797c0d73",
221
"url": "https://console.aws.amazon.com/cloudwatch/home?region=us-west-2#logsV2:log-groups/..."
222
}
223
}
224
```
225
226
## Layer Integration
227
228
Use Sentry's pre-built AWS Lambda layer for simplified deployment:
229
230
1. Add the Sentry Lambda layer to your function
231
2. Set environment variables:
232
- `NODE_OPTIONS`: `-r @sentry/serverless/build/npm/cjs/awslambda-auto`
233
- `SENTRY_DSN`: Your Sentry DSN
234
- `SENTRY_TRACES_SAMPLE_RATE`: Sample rate for performance tracing
235
236
The layer automatically initializes Sentry and wraps your handler without code changes.
237
238
## Error Handling
239
240
The Lambda integration provides sophisticated error handling:
241
242
- **Automatic Exception Capture**: All uncaught exceptions are automatically captured
243
- **Promise Rejection Handling**: Unhandled promise rejections are captured
244
- **Timeout Warnings**: Configurable warnings before Lambda timeout
245
- **Context Preservation**: Lambda context is preserved in error reports
246
- **Event Flushing**: Ensures events are sent before Lambda terminates
247
248
## Performance Tracing
249
250
Automatic performance tracing capabilities:
251
252
- **Handler Tracing**: Each Lambda invocation is traced as a transaction
253
- **Distributed Tracing**: Continues traces from incoming requests (API Gateway, etc.)
254
- **AWS Service Calls**: Automatically traces AWS SDK calls (when AWS services integration is enabled)
255
- **Custom Spans**: Add custom spans within your handler logic
256
257
```typescript
258
import { AWSLambda, startSpan } from "@sentry/serverless";
259
260
exports.handler = AWSLambda.wrapHandler(async (event, context) => {
261
// Custom span within handler
262
return await startSpan({ name: "process-event", op: "function" }, async (span) => {
263
// Your processing logic
264
span.setTag("event-type", event.type);
265
return await processEvent(event);
266
});
267
});
268
```